dimanche 1 mars 2015

Rails: Checkboxes for Many-to-Many Relationship with hidden fields

I'm building an application (web/iOS) that allows a user to set a series of preference options. The models/tables required include:



  • Users: stores user name, password, email address

  • Prefs: stores names/classes of preferences available, i.e., "sex"

  • PrefOpts: stores options for each preference, i.e., "Male" and "Female" for sex

  • UserPrefs: stores a selected PrefOpt for each User for each Pref


Model Specs:



class User < ActiveRecord::Base
has_many :user_prefs
has_many :prefopts, through: :user_prefs

end

class Pref < ActiveRecord::Base
has_many :prefopts
has_many :user_prefs

accepts_nested_attributes_for :prefopts

validates :name, presence: true
end

class Prefopt < ActiveRecord::Base
belongs_to :pref
has_many :user_prefs
has_many :users, through: :user_prefs

accepts_nested_attributes_for :user_prefs
end

class UserPref < ActiveRecord::Base
belongs_to :user
belongs_to :prefopt
end


For now, I want to set the user's preferences/options on the user "show" page, so when I pull up a user's record, I see a listing of all the preferences and for each a drop-down list of the available preferences for each option.


I have updated the Users controller to query back the preferences...



# GET /users/1
# GET /users/1.json
def show
@prefs = Pref.all
end


Also, I added to the routes file references under users:



resources :users do
resources :prefs do
get 'prefopts', on: :member
end
end


And this works fine: on a user's "show" page I can see all the available preferences when using this syntax:



<p>
<H2>Preferences</H2>
<ul>
<% @prefs.each do |pref| %>
<li><%= pref.name %></li>
<ul>
</ul>

<% end %>
</ul>
</p>


Now, I want to create a series of check-boxes with each option available for each preference. From other examples, I've put together this:



<%= form_for(@user) do |f| %>
<%= f.hidden_field :user_id, :value => @user.id %>
<H2>Preferences</H2>
<ul>
<% @prefs.each do |pref| %>
<li><%= pref.name %></li>
<%= f.fields_for :user_prefs, @user.user_prefs.find_or_initialize_by(pref_id: pref.id) do |u| -%>
<%= u.hidden_field :pref_id, pref.id %>
<%= u.collection_check_boxes(:user_pref, :pref_opt_ids, pref.prefopts, :id, :name) %>
<% end -%>

<% end %>
</ul>
</p>


The error I'm getting is on the line with find_or_initialize_by and is: undefined method `merge' for 1:Fixnum


I'd greatly appreciate any assistance you can give me!





Aucun commentaire:

Enregistrer un commentaire