【问题标题】:Rails has_many association with multiple keysRails has_many 与多个键的关联
【发布时间】:2011-07-14 12:52:47
【问题描述】:

我正在尝试绕过旧数据库。每个表都有一个“数据源”列,该列是数据来源的 3 个字符代码。因此,为了唯一标识并与其他表相关联,您必须拥有两条信息(例如帐号和数据源)。

除非我尝试在查询中包含,否则我在下面的 has_many 关系工作正常。

# Model Association
has_many :transactions,
         :primary_key => :account,
         :foreign_key => :acnt,
         :order => :ddate,
         :conditions => ['datasource = ?', '#{self.datasource}']

# Controller code FAIL when I loop through results in view and call 'account.transactions'
@accounts = Account.includes(:transactions).where(:lname => 'Smith')

# However, this controller code works when I loop through the results in the view and call 'account.transactions'
@accounts = Account.where(:lname => 'Smith')

# View
<% @accounts.each do |a| %>
  <% a.transactions.each do |t| %>
    <%= t.description %>
  <% end %>
<% end %>

错误:

ActionView::Template::Error (undefined method `datasource' for #<Class:0x1025f25c8>):

在 Rails 3 中实现此目的的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord associations models


    【解决方案1】:

    分解并定制了finder_sql。看起来它有效,到目前为止......

      has_many :transactions,
               :primary_key => :account,
               :foreign_key => :acnt,
               :finder_sql =>
                   'SELECT t.* ' +
                   'FROM accounts a, transactions t ' +
                   'WHERE a.acnt = t.account AND a.datasource = t.datasource ' +
                   'ORDER BY t.ddate'
    

    【讨论】:

      【解决方案2】:

      尝试将您的条件放在引号内

      has_many :transactions,
               :primary_key => :account,
               :foreign_key => :acnt,
               :order => :ddate,
               :conditions => ['datasource = "#{self.datasource}"']
      

      【讨论】:

      • self.datasource 将引发错误,因为数据源不是类属性。 self 在这里指的是 Account 类而不是实例。
      • 你错了,因为self 是父母的(transaction.account)对象(实际上是实例)。
      • 我遇到了同样的错误。不过,仅在使用 Account.includes() 时。
      • @Deepak N,对不起,当我们使用 Model.includes(assoc) 时,self 将返回 Model 对象,而当我们使用 Model.last.assoc self will return Model` 实例时。这才是真正的主题问题
      【解决方案3】:

      你的条件语句是错误的。试试这个。

      :条件 => ['事务.数据源 = account.datasource']

      【讨论】:

      • 使用has_many时,“accounts”表不在FROM语句中,故此条件无效。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      相关资源
      最近更新 更多