I'm using simple_form and collection_check_boxes in this form:
<%= simple_form_for(@geo_path_media_type) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :name %>
<%= f.input :category %>
<%= f.collection_check_boxes :required_fields, [{ :id => 1, :name => 'chris'}, { :id => 2, :name => 'damn'}], :id, :name, checked: [{ :id => 1, :name => 'chris'}, { :id => 2, :name => 'damn'}].map(&:id) do |b| %>
<span>
<%= b.check_box %>
<%= b.label %>
</span>
<% end %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
I get the error:
undefined method 'id' for {:id=>1, :name=>"chris"}:Hash
Using a collection like User.all works fine, i.e.:
<%= f.collection_check_boxes :required_fields, User.all, :id, :name, checked: User.all.map(&:id) do |b| %>
Why can't I use a hash here?
A hash requires you to access the :id key using hash[:id]. Rails generate getter methods for all columns in an ActiveRecord class as a default, meaning you can call, for example, user.id.
You can use an OpenStruct to achieve this:
x = OpenStruct.new(:id: 1, name: 'chris')
x.id #=> 1
In your case:
<%= f.collection_check_boxes :required_fields, [OpenStruct.new(:id: 1, name: 'chris'), OpenStruct.new(:id: 2, name: 'damn')], :id, :name #.....
Hope that helps - let me know if you've any questions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With