Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 4 更新已联接多个表的最佳方法_Ruby On Rails 4_Has Many Through_Model Associations_Jointable - Fatal编程技术网

Ruby on rails 4 更新已联接多个表的最佳方法

Ruby on rails 4 更新已联接多个表的最佳方法,ruby-on-rails-4,has-many-through,model-associations,jointable,Ruby On Rails 4,Has Many Through,Model Associations,Jointable,现在我有一张工作表 has_many :applicants has_many:users, through: :applicants belongs_to :job belongs_to :user has_many :applicants has_many:jobs, through: :applicants 还有一张申请表 has_many :applicants has_many:users, through: :applicants belongs_to :jo

现在我有一张工作表

  has_many :applicants
  has_many:users, through: :applicants
belongs_to :job
belongs_to :user
has_many :applicants
has_many:jobs, through: :applicants
还有一张申请表

  has_many :applicants
  has_many:users, through: :applicants
belongs_to :job
belongs_to :user
has_many :applicants
has_many:jobs, through: :applicants
和一个带有

  has_many :applicants
  has_many:users, through: :applicants
belongs_to :job
belongs_to :user
has_many :applicants
has_many:jobs, through: :applicants
所以用户通过申请表连接到作业表,反之亦然

我不确定我是否正确更新了模型。现在看起来是这样的:

def addapply
    @job = Job.find(params[:id])
    applicant = Applicant.find_or_initialize_by(job_id: @job.id)
    applicant.update(user_id: current_user.id)
    redirect_to @job
end
但我开始思考——这会不会取代以前存在的任何关联

我开始四处寻找,在其他人的代码中发现:

def update

  unless params[:user_relationships][:user_category_ids]
    # Set default user category if not selected.
    @user.user_category_relationships.build(
      :category_id        => '1',
      :created_by_user_id => @current_user.id,
      :name_id            => @name.id
    )
  else
    params[:user_relationships][:user_category_ids].each { |user_category_id|
      @user.user_category_relationships.build(
        :category_id        => user_category_id,
        :created_by_user_id => @current_user.id,
        :name_id            => @name.id
      )
    }
  end
end
我不确定这一切是如何工作的,但也许我确实需要在更新之前用.each遍历它们

我不想取代已经存在的东西,我只想补充一下

简而言之,更新(或者更确切地说是添加)has\u many的最佳方法是什么:通过联接表关联?

为什么不

def addapply
  @job = Job.find(params[:id])
  applicant = Applicant.where(job_id: @job.id, user_id: current_user.id).first_or_create
  redirect_to @job
end