ruby - Strange has_many Association Behavior in Rails 4 -


i've got 2 tables, user , allergy. these connected via table, userallergy. models expected:

class user   has_many :user_allergies   has_many :allergies, through: :user_allergies end  class userallergy   belongs_to :user   belongs_to :allergy end  class allergy   has_many :user_allergies   has_many :users, through :user_allergies end 

what i'm confused creating allergies multiple-valued collection_select in user form.

i have following field:

<%= f.collection_select :allergy_ids,                          allergy.all,                          :id,                          :name,                          {},                          { class: 'form-control', multiple: true } %> 

this correctly inserts key params if selected allergies ids 1 , 2:

{ user: { id: "1", allergy_ids: ["", "1", "2"] } } 

when create user instantiated @user = user.new( my_params ), weird behavior occurs. instead of inserting provided allergy_ids join table, rails query current user_allergies user, deletes of current user_allergies:

started patch "/employees/regular_user" 127.0.0.1 @ 2015-06-18 22:08:30 -0400 processing userscontroller#update html   parameters: {"utf8"=>"✓", "user"=>{ "allergy_ids"=>["", "1", "2", "3"]}, "button"=>"", "id"=>"regular_user"}   cache (0.0ms)  select  "users".* "users" "users"."id" = ? limit 1  [["id", 2]]    (0.1ms)  begin transaction   allergy load (0.1ms)  select "allergies".* "allergies" inner join "user_allergies" on "allergies"."id" = "user_allergies"."allergy_id" "user_allergies"."user_id" = ?  [["user_id", 1]]   sql (0.1ms)  delete "user_allergies" "user_allergies"."user_id" = ? , "user_allergies"."allergy_id" = 1  [["user_id", 1]]    (27.4ms)  commit transaction redirected http://localhost:3000/employees/regular_user completed 302 found in 32ms (activerecord: 27.8ms) 

anyone knows gives, or need create allergies implicitly? i've tried accepts_nested_attributes_for , changing around form use fields_for.

so, went , looked @ code of mine similar function. here's create method looks like. creating student assignment student groups in school setting (i didn't use "class" since ruby wouldn't that).

def create   @student = student.new(student_params)    if @student.save     @student.student_groups = studentgroup.where(id: params[:student][:student_group_ids])     flash[:success] = "student created."     redirect_to @student   else     render 'new', notice: "your student not created."   end end 

i ignore student group ids when creating student_params, since i'm not using them mass assignment.

yes, 1 line of code. i'd interested hear if there's way accomplish via mass assignment.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -