Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Creating has_many relations in multiple select field #34

Closed
jtruzzi opened this issue Sep 9, 2017 · 4 comments
Closed

Creating has_many relations in multiple select field #34

jtruzzi opened this issue Sep 9, 2017 · 4 comments

Comments

@jtruzzi
Copy link

jtruzzi commented Sep 9, 2017

Hi! I wanted to know if it's posible to add, to the edit form, a multiple select field for a has_many relationship. I tried with collection_check_boxes and it shows all the checkboxes, but it won't save. Also tried with collection_select and services, but it's not a multiple select and i won't save either.

Love the admin! I hope this is possible

Thanks!

@spohlenz
Copy link
Member

Here is some sample code required to collection_select or collection_check_boxes work:

collection_select :author_ids, User.all, :id, :name, { label: "Author(s)" }, { multiple: true }

or

collection_check_boxes :author_ids, User.all, :id, :name, { label: "Author(s)" }

There might be a couple of things that are tripping you up: a) Make sure you use the _ids suffix on the field name, or b) For selects, { multiple: true } is a separate, second options hash (for HTML options). You can use an empty hash for the first options hash if you don't need to set a custom label.

@spohlenz
Copy link
Member

Closing. Feel free to re-open if it hasn't solved your issue.

@jtruzzi
Copy link
Author

jtruzzi commented Sep 15, 2017

Hi sorry for the delay, i just tried it but i'm getting a "undefined method `services_ids' for #<Hotel" (that field is has_many relation to another model) . And when i remove the suffix, i get the multiple checkboxs showing correctly in the form, but when i post i get " #<ActiveRecord::AssociationTypeMismatch: Service(#70191805563060) expected, got String(#70191807635240)>".

Any idea what am i doing wrong?

@spohlenz
Copy link
Member

Try with :service_ids (service is singular). This is a method defined by Rails when you declare a has_many association (http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many).

Without the _ids suffix, it is trying to assign the IDs (array of strings) to the association, when it is expecting an array of Service objects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants