【问题标题】:Best way to update Has_many Joined Table更新 Has_many Joined Table 的最佳方式
【发布时间】:2014-01-03 19:52:00
【问题描述】:

现在我有一个带有

的工作表
  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_many 的最佳方法是什么:通过连接表关联?

【问题讨论】:

    标签: ruby-on-rails-4 has-many-through model-associations jointable


    【解决方案1】:

    为什么不呢?

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 2018-05-14
      • 2013-04-06
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多