将属性插入连接表

时间:2018-06-10 01:12:37

标签: ruby-on-rails postgresql activerecord

每当我通过AR模型插入时,我想在连接表属性中插入一个值。我正在使用与所有受影响模型的HMT关联。

它的安排如下......我有一个帐户表模型:

class TabAccount < ApplicationRecord
  has_many :tab_client_project_accounts
  has_many :tab_projects, through: :tab_client_project_accounts
end

使用连接表模型:

class TabClientProjectAccount < ApplicationRecord
  belongs_to :tab_account
  belongs_to :tab_project
end

加入项目表模型:

class TabProject < ApplicationRecord
  has_many :tab_client_project_accounts
  has_many :tab_accounts, through: :tab_client_project_accounts
end

在我的控制器中,我使用铲子操作员为项目添加帐户:

@this_project.tab_accounts << _new_account unless @this_project.tab_accounts.include?(_new_account)

它按设计工作。但是我也希望在我的tab_client_project_accounts连接表中插入一个值作为该铲运算符的一部分。那可能吗?这样做的正常最佳做法是什么?

3 个答案:

答案 0 :(得分:2)

如果在连接表中需要更多列,<<方法(未明确使用连接表)将无法工作,因为它没有设置任何其他属性。您可以改为使用连接模型:

您的版本(没有联接表):

@this_project.tab_accounts << _new_account unless @this_project.tab_accounts.include?(_new_account)

使用联接表:

@this_project.tab_client_project_accounts.build(
  tab_account: _new_account, 
  additional_data: 'anything_you_need'
) unless @this_project.tab_accounts.include?(_new_account)

答案 1 :(得分:0)

这是你可以做的事情

tp = TabProject.find 1

tp.tab_client_project_accounts.build tab_account: TabAccount.find 1

tp.tab_client_project_accounts.build tab_account: TabAccount.create(name: 'Some Account Name')

tp.save!

这将确保所有表格中的记录

答案 2 :(得分:0)

我让它按预期工作;这就是我所拥有的:

_account_type_list_member_id = RefAccountType.find_by_typename('List Member').id

@this_project.tab_client_project_accounts.build(
  :tab_account => _new_account,
  :ref_account_type_id => _account_type_list_member_id
).save unless @this_project.tab_accounts.include?(_new_account)