saving record to join table Has_many :through - ruby-on-rails-3

I am new to Rails 3 and having trouble with saving records in the Join table. I have been looking around and trying different examples found on this website and from the documentation or books, but I don't understand why I can't get it to work. I am trying to create Authorization by creating Roles and associate them to users. So far I have been trying to assign roles from the update action in the Users controller without prevail.
I have 3 models: the User.rb, role.rb, and assignment.rb (the join table)
class User < ActiveRecord::Base
has_many :assignments, :dependent => :destroy
has_many :roles, :through => :assignments, :foreign_key => :role_id
accepts_nested_attributes_for :roles
attr_accessor :password, :role_ids
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :status, :description, :username, :roles_attributes
...
end
class Role < ActiveRecord::Base
has_many :assignments
has_many :users, :through => :assignments, :foreign_key => :user_id
accepts_nested_attributes_for :users
attr_accessible :name
end
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
accepts_nested_attributes_for :roles
end
The Users controller in the update action I have the following
class UsersController < ApplicationController
...
def update
#user = User.find(params[:id])
if #user.update_attributes(params[:user])
#user.roles.build
flash[:success] = "Profile updated"
redirect_to #user
else
#title = "Edit" + " " + #user.username
render 'edit'
end
end
...
end
and in the 'edit' view page I intend to have checkboxes to update the User record with an associated role:
EDIT: Changed the "check_box" with "check_box_tag" ... the check boxes appear properly, but the values are not saved.
<%= form_for(#user) do |f| %>
...
<div class="field">
<%= f.label :roles %><br />
<%= f.fields_for :role_ids do |r| %>
<% #roles.each do |role| %>
<%= check_box_tag "user[roles][]", role.id, #user.roles.include?(role.id) %>
<%= role.name %>
<% end %>
<%= hidden_field_tag "user[roles][]", "" %>
<% end %>
</div>
<% end %>
With this code I even get an error where 'Roles' have no association.
EDIT: this was corrected with the accepts_nested_attributes_for :role. Thanks!
No association found for name `roles'. Has it been defined yet?
I am really confused where I am doing something wrong. Your help would be much appreciated.
Aurelien

You have to use the same name with "accepts_nested_attributes_for" as you used defining the association:
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
accepts_nested_attributes_for :role
end

Finally solved the problems and thought I could share.
The models associations but I did change the attr_accessible:
class User < ActiveRecord::Base
has_many :assignments, :dependent => :destroy
has_many :roles, :through => :assignments, :foreign_key => :role_id
accepts_nested_attributes_for :roles
attr_accessor :password
attr_accessible ..., :roles_ids
...
end
In the User controller for the edit and update action.
def edit
#title = "Edit" + " " + #user.username
#roles = Role.find(:all)
#user.assignments.build
end
def update
#user = User.find(params[:id])
if #user.update_attributes(params[:user])
flash[:success] = "Profile updated"
redirect_to #user
else
#title = "Edit" + " " + #user.username
render 'edit'
end
end
The important part was the view part and assigning the right names for the checkbox tags
<%= form_for(#user) do |f| %>
<div class="field">
<%= f.label :roles %><br />
<%= f.fields_for :role_ids do |r| %>
<% #roles.each do |role| %>
<%= check_box_tag "user[role_ids][]", role.id, #user.roles.include?(role) %>
<%= role.name %>
<% end %>
<%= hidden_field_tag "user[role_ids][]", #user.id %>
<% end %>
</div>
The check_box_tag lets the form save an array and gives more control than check_box
Then in order to assign the multiple Role ids, the name of the check_box_tag should include user[roles_ids][].
Finally the last parameter of the check_box_tag returns if the User has already the roles and checks the checkboxes if true.
I must admit that the name part of the check_box_tags is really confusing but it works :).

Related

Rails: multi level nested Forms (accepts nested attributes)

I am creating simple blog level application. below are my models.
class User < ActiveRecord::Base
attr_accessible :name,:posts_count,:posts_attributes , :comments_attributes
has_many :posts
has_many :comments
accepts_nested_attributes_for :posts , :reject_if => proc{|post| post['name'].blank?} , :allow_destroy => true
end
class Post < ActiveRecord::Base
attr_accessible :name, :user_id ,:comments_attributes
belongs_to :user
has_many :comments
accepts_nested_attributes_for :comments
end
class Comment < ActiveRecord::Base
attr_accessible :content, :post_id, :user_id
belongs_to :user
belongs_to :post
end
I am trying to create user,post and comment in one form by using accepts_nested_attributes_for feature of rails. Below is my controller and view code.
Controller-----------
class UsersController < ApplicationController
def new
#user = User.new
#post = #user.posts.build
#post.comments.build
end
def create
#user = User.new(params[:user])
#user.save
end
end
Form----------
<%= form_for #user do |f| %>
<%= f.text_field :name %>
<%= f.fields_for :posts do |users_post| %>
<br>Post
<%= users_post.text_field :name %>
<%= users_post.fields_for :comments do |comment| %>
<%= comment.text_field :content %>
<% end %>
<% end %>
<%= f.submit %>
<% end %>
With the above code i am successfully able to create new user,post and comment but the problem is that i am not able to assign newly created user to newly created comment.when i checked the newly created comment into the database i got below result.I am getting user_id field value of "nil".
#<Comment id: 4, user_id: nil, post_id: 14, content: "c", created_at: "2014-05-30 09:51:53", updated_at: "2014-05-30 09:51:53">
So I just want to know how we can assign newly created comment to newly created user???
Thanks,
You will have to explicitly assign user_id for comments! You are nesting comments under posts, so comments would be having post_id assigned by default but though you are nesting comments under user form indirectly, there is no direct nesting of comments under user, so user_id remains blank in comments.
Try writing after create callback in Comment model to set user_id
In comment.rb
after_create{|comment|
comment.user_id = post.user_id
comment.save
}
Hope this helps :)

why are my new and create actions not working with accepts_nested_attributes_for with has_many through?

I'm building a rail 3.2.16 app using 3 models related with a has_many through association but my saving actions are not working. this are my models:
class Cliente < ActiveRecord::Base
has_many :prestamos
accepts_nested_attributes_for :prestamos, reject_if: :all_blank
end
class User < ActiveRecord::Base
has_many :prestamos
has_many :clientes, :through => :prestamos
end
class Prestamo < ActiveRecord::Base
validates_numericality_of :monto, only_integer: true
validates :monto, presence: true
belongs_to :user
belongs_to :cliente, inverse_of: :prestamos
end
When I try to build my #cliente in clientes_controller#new with this
#cliente = current_user.clientes.build
and this in #create
#cliente = current_user.clientes.build(params[:cliente])
and using this view
<%= simple_form_for(#cliente) do |f| %>
<%= f.input :nombre %>
<%= f.input :cedula %>
<%= f.input :direccion %>
<%= f.simple_fields_for :prestamos do |builder| %>
<%= builder.input :monto %>
<% end %>
<%= f.button :submit %>
<% end %>
The render HTML is the expected one, but on save I got the validations errors related to monto in prestamo model. By the way, the monto field is displayed twice.
The erros I having:
Prestamos monto is not a number
Prestamos monto can't be blank
I really hope someone can help me.
Thanks in advance.
Well, I could solve it, but I'm not sure if this is the best way to do it since I'm pretty new in Rails (3 month). This is what I did:
First, I changed my join model Prestamo to this:
class Prestamo < ActiveRecord::Base
attr_accessible :monto, :user_id, :cliente_id
validates_numericality_of :monto, only_integer: true
validates :monto, presence: true
belongs_to :user
belongs_to :cliente, inverse_of: :prestamos
end
The validation were there already, I just added :user_id to the attr_accessible.
2nd, I changed my new and create actions to this:
new:
def new
#cliente = Cliente.new
#cliente.prestamos.build(user_id: current_user.id)
end
create:
#cliente = Cliente.new(params[:cliente])
Finally, I added a hidden field to my form just to store the user_id
<%= form.simple_fields_for :prestamos do |f| %>
<%= f.input :monto %>
<%= f.input :user_id, as: :hidden %>
<% end %>

Rails 3 my first nested form doesnt work - Can't mass-assign protected attributes

I'm creating my first nested form in Rails 3.2.13. User is registering and he fill email, password and address information and company information.. but the error is showing while user click on submit. Error is at the bottom.
Im not sure about this line: attr_accessible :address_attributes, :company_attributes
which i read it could help but it doesnt and i have addresses in the view but address in the model because of one-to-one relationship but if i have <%= f.fields_for :**address** do |builder| %> the form doesnt show up.
Please what i have to do ? :-)
The post sends then
"companies"=>{"name"=>"Companyname"
User model
class User < ActiveRecord::Base
attr_accessible ...
has_many :orders
belongs_to :address
belongs_to :company
accepts_nested_attributes_for :address, :company
attr_accessible :address_attributes, :company_attributes
Company model
class Company < ActiveRecord::Base
attr_accessible ...
has_many :users
validates_presence_of ...
end
Address model
class Address < ActiveRecord::Base
attr_accessible ...
has_many :orders, :foreign_key => 'payment_address_id'
has_many :orders, :foreign_key => 'delivery_address_id'
has_many :users
validates_presence_of ...
end
new.html.erb (creating new user)
<%= form_for #user do |f| %>
...
<%= f.fields_for :addresses do |builder| %>
...
<% end %>
<%= f.fields_for :companies do |builder| %>
...
<% end %>
<%= f.submit %>
<% end %>
error while i click on submit
Can't mass-assign protected attributes: addresses, companies
EDIT:
First mistake: i changed in Class User
belongs_to :address
belongs_to :company
on
has_one :address
has_one :company
and in Address and Company model i edit
has_many :users
on
belongs_to :user
but nested forms doesnt show up in the view.. i tried edit Users Controller by adding .build method
def new
#user = User.new
#user.company.build
#user.address.build
end
but im getting new error
undefined method `build' for nil:NilClass
please what i have to do now ?
I had a case like this a day ago, and that's what I used.
class User
attr_accessible :name, :email, :company_attributes, :address_attributes
has_one :company
accepts_nested_attributes_for :company
end
and EmailSetting:
class Company
belongs_to :user
end
after this I can run in console:
User.new.build_company
as for form:
<%= form_for #user do |f| %>
<%= f.fields_for :company do |builder| %>
<%= f.text_field :name %>
<% end %>
<% end %>
in controller you just initialize the #user variable, no need to do #user.company.build or #user.address.build

Rails - Nested Model Fails to Save

I'm rather new to Rails and I'm writing a signup form that includes nested models. When I submit the form, the user is saved just fine, but the nested model does not save anything to the Subscription db, and the console throws no errors.
I sincerely hope I'm not missing something insanely obvious, and I appreciate any tips you can share. Thanks!
Here is the code-
Models:
class Plan < ActiveRecord::Base
attr_accessible :posts, :name, :price
has_many :users
end
class User < ActiveRecord::Base
belongs_to :plan
has_many :events
has_one :subscription, :autosave => true
accepts_nested_attributes_for :subscription
attr_accessible :subscription_attributes
def save_with_payment
if valid?
customer = Stripe::Customer.create(
email:email,
plan: plan_id,
card: stripe_card_token )
self.stripe_customer_token = customer.id
save!
end
rescue Stripe::InvalidRequestError => e
logger.error "Stripe error while creating customer: #{e.message}"
errors.add :base, "There was a problem with your credit card."
false
end
end
class Subscription < ActiveRecord::Base
attr_accessible :plan_id, :status, :user_id
belongs_to :user
end
This is the User controller:
def new
#user = User.new
plan = Plan.find(params[:plan_id])
#user = plan.user
#user.build_subscription
end
def create
#user = User.new(params[:user])
if #user.save_with_payment
sign_in #user
flash[:success] = "Welcome to the SendEvent!"
redirect_to #user
else
render 'new'
end
end
This is the form:
<%= form_for #user, :html => {:class => "form-inline"} do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="control-group">
<%= f.label :name, :class => "control-label" %>
<%= f.text_field :name %>
</div>
# A few more fields here and...
# The nested model:
<%= f.fields_for :subscription do |builder| %>
<%= builder.hidden_field :status, :value => true %>
<% end %>
<%= f.submit "Create my account", class: "btn btn-large btn-primary", id: "submitacct" %>
<% end %>
Sample app from RailsCasts
RailsCasts Episode #196: Nested Model Form (revised)
Maybe help you.

creating a join action between user and group correctly

I have a problem when trying to create a membership for users based on the name they input into the membership form - new.html.erb.
user.rb
has_many :memberships, :dependent => :destroy
has_many :groups, :through => :memberships
membership.rb
class Membership < ActiveRecord::Base
attr_accessible :user_id, :group_id
belongs_to :user
belongs_to :group
end
group.rb
has_many :memberships, :dependent => :destroy
has_many :users, :through => :memberships
membership controller
def create
#group = Group.find_by_name(:group)
#membership = current_user.memberships.build(:group_id => #group.group_id)
if #membership.save
flash[:notice] = "You have joined this group."
redirect_to :back
else
flash[:error] = "Unable to join."
redirect_to :back
end
end
membership - _form.html.erb
<%= form_for(#membership) do |f| %>
...
#error validation
...
<div class="field">
<%= f.label :group %><br />
<%= f.text_field :group %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
What I want it to do is find the group inputted if it exists, and create the table entry in the memberships table accordingly. Just not sure if what I'm doing is on the right track. Any suggestions?
The reason your code isn't working now is because of this line:
#group = Group.find_by_name(:group)
it should be something like (I don't remember exactly sorry)
#group = Group.find_by_name(params[:membership][:group])
The error is getting called on the next line because #group is nil.
But you should probably handle that type of logic in the model anyway with a virtual attribute or something.
membership.rb
def group_name
if self.group
#group_name ||= self.group.name
end
end
def group_name=(group_name)
#group_name = group_name
self.group = Group.find_by_name(#group_name)
end
form
<div class="field">
<%= f.label :group_name, "Group" %><br />
<%= f.text_field :group_name %>
</div>
controller
def create
#membership = current_user.memberships.build(params[:membership])
if #membership.save
flash[:notice] = "You have joined this group."
redirect_to :back
else
flash[:error] = "Unable to join."
redirect_to :back
end
end