Sunday 15 February 2015

ruby - Rails 4 drop down select list different model -


New to rail should be easy for me: -)

I have 2 models: user and Role:

  Class User & lt; ActiveRecord :: Base is_mind: Accepting roles_for all_images_rights: roles validates_presence_of: role_id role of end class & lt; ActiveRecord :: Base is_to: User's End  

There is a role_ID for the user's foreign key.

All I'm trying to do is enable the user to choose a role for this user / new look, I know that this is easy, but I do not understand ... I really like nowadays I am studying for hours, I am trying to understand it. The drop-down selection appears in the list view, but it always fails verification (as it shows, but does not always select the user with the user. Lola_ID)

For me here What I have is partial to show the drop down:

  <% = f.collection_select: role_id, Role.all ,: id ,: name% & gt;  

Can someone tell me in the right direction? Maybe I have to use some kind of nested forms, but I have not tried anything and I think that I currently have it. Do I have to do something in my controller?

If the user has many roles, then your user should not have a model: field User_id , I think, and I hope, that the users are near many roles and represent them. Then you need a third model:

  class user & lt; ActiveRecord :: Base has has_many: user_roles has_many: roles, via: user_roles role of the end class & lt; ActiveRecord :: Base has_many: user_roles has_many: User, through: user_roles End class UserRole & lt; You can use it to update your relationship (see: : role_ids  / Code> in plural) 

  & lt;% = f.collection_select: role_ids, Role.all ,: id,: name, {}, {multiple: true}%>  

And verification is now in the user model.

Edit : If you are using Rail 4.x then you are allowed a parameter of Role_ids.

  params.require (: user) .permit (: user_field1 ,: user_field2, ..., role_ids: [])  

No comments:

Post a Comment