如何通过关联访问has_many的表

时间:2014-01-31 04:25:26

标签: ruby-on-rails

说我有以下关联。

class Supplier < ActiveRecord::Base
  has_one :account
  has_one :account_history, through: :account
end

class Account < ActiveRecord::Base
  belongs_to :supplier
  has_one :account_history
end

class AccountHistory < ActiveRecord::Base
  belongs_to :account
end
  1. 如何通过供应商模式访问帐户表
  2. 如何通过帐户模型访问供应商表
  3. 如何在不通过其他模式
  4. 的情况下访问联接表accounthistory
  5. 如何通过迁移到accounthistory添加字段,然后通过供应商或帐户模型从该字段获取值

1 个答案:

答案 0 :(得分:0)

当然这太简单了,但这就是我的建议:

<强> 1。 @supplier.account

@supplier = Supplier.find(id)
@supplier.account #-> brings account data

<强> 2。 @account.supplier

@account = Account.find(id)
@account.supplier #-> brings supplier data

第3。 @supplier.account_history

@supplier = Supplier.find(id)
@supplier.account_history #-> brings account_history

<强> 4。迁移

def change
    add_column :account_histories, :your_column, :type, after: :column
end

您可以直接处理连接模型/表(与HABTM不同),这意味着您可以根据需要创建迁移。上面的迁移代码显示了如何直接向表中添加列

<强>代表

要从该模型访问数据,您很幸运

因为您使用的是单一关联(has_one / belongs_to),所以您应该可以delegate调用另一个模型:

#app/models/supplier.rb
Class Supplier < ActiveRecord::Base
  has_one :account
  has_one :account_history, through: :account
end

#app/models/account.rb
class Account < ActiveRecord::Base
  belongs_to :supplier
  has_one :account_history

  delegate :extra, :vars, :here, to: :account_history
end

这将允许您致电:@supplier.account.extra

希望这有帮助吗?你的问题在上下文中很少,所以如果你更新,我可以修复我的答案!