Rails中的奇怪的has_many关联行为4

时间:2015-06-19 02:12:02

标签: ruby-on-rails ruby ruby-on-rails-4 models

我有两张桌子UserAllergy。它们通过另一个表UserAllergy连接。模型如预期的那样:

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

我感到困惑的是以collection_select形式从多值User创建过敏症。

我有以下字段:

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

如果我选择带有ID 1和2的Allergies,这会正确地将一个键插入我的参数中:

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

当我创建用@user = User.new( my_params )实例化的用户时,会发生奇怪的行为。 Rails不会将提供的allergy_ids插入到连接表中,而是执行查询以获取用户的所有当前user_allergies,然后删除所有当前user_allergies

Started PATCH "/employees/regular_user" for 127.0.0.1 at 2015-06-18 22:08:30 -0400
Processing by UsersController#update as HTML
  Parameters: {"utf8"=>"✓", "user"=>{ "allergy_ids"=>["", "1", "2", "3"]}, "button"=>"", "id"=>"regular_user"}
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]
   (0.1ms)  begin transaction
  Allergy Load (0.1ms)  SELECT "allergies".* FROM "allergies" INNER JOIN "user_allergies" ON "allergies"."id" = "user_allergies"."allergy_id" WHERE "user_allergies"."user_id" = ?  [["user_id", 1]]
  SQL (0.1ms)  DELETE FROM "user_allergies" WHERE "user_allergies"."user_id" = ? AND "user_allergies"."allergy_id" = 1  [["user_id", 1]]
   (27.4ms)  commit transaction
Redirected to http://localhost:3000/employees/regular_user
Completed 302 Found in 32ms (ActiveRecord: 27.8ms)

任何人都知道隐含地产生过敏症的原因是什么,或者我需要做些什么?我已尝试accepts_nested_attributes_for并更改表单以使用fields_for

3 个答案:

答案 0 :(得分:1)

所以,我去看了我的代码,它具有类似的功能。这是我的创建方法的样子。这是在学校环境中创建一个学生小组的学生(我没有使用&#34;课程&#34;因为Ruby不会那样)。

def create
  @student = Student.new(student_params)

  if @student.save
    @student.student_groups = StudentGroup.where(id: params[:student][:student_group_ids])
    flash[:success] = "Student was successfully created."
    redirect_to @student
  else
    render 'new', notice: "Your student could not be created."
  end
end

我在创建student_params时完全忽略了学生组ID,因为我没有使用它们进行批量分配。

是的,还有一行代码。我真的很想知道是否有办法通过批量分配来实现这一目标。

答案 1 :(得分:0)

你错过了谜题的一部分,即从过敏到用户的关系。

class Allergy
  has_many :user_allergies
  has_many :users, through: :user_allergies
end

答案 2 :(得分:0)

试试下面的代码 -

params.require(:user).permit(___, ____, {allergy_ids: []}, ____, ____)