2011-03-13 71 views
2

我试图弯曲传统数据库周围的轨道。每个表都有一个'数据源'列,它是数据来源的3个字符的代码。因此,为了唯一标识和关联其他表格,您必须拥有两条信息(例如帐号和数据源)。Rails has_many与多个键的关联

我有下面的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中做到这一点的正确方法?

+0

显示你的错误 – fl00r 2011-03-13 17:03:19

回答

0

您的病情陈述是错误的。尝试这个。

:conditions => ['transactions.datasource = accounts.datasource']

+0

使用的has_many“户口”当表不在FROM语句,因此这种情况下是无效的。 – robotshapes 2011-03-13 17:48:37

1

尝试把你的病情报价

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

self.datasource将引发错误,因为datasource不是类属性。自我指的是Account类,这里不是实例。 – 2011-03-13 17:42:30

+0

你错了,因为'self'是父项(transaction.account)对象(实际是实例)。 – fl00r 2011-03-13 17:44:09

+0

这不适合我。 – robotshapes 2011-03-13 17:51:05

2

抛锚和定制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' 
+0

非常好的问题:)收藏 – fl00r 2011-03-13 19:04:23