我正在尝试围绕旧数据库弯曲rails。每个表都有一个'datasource'列,它是数据来源的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中实现此目的的正确方法是什么?
答案 0 :(得分: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'
答案 1 :(得分:1)
尝试将您的条件置于引号
之内has_many :transactions,
:primary_key => :account,
:foreign_key => :acnt,
:order => :ddate,
:conditions => ['datasource = "#{self.datasource}"']
答案 2 :(得分:0)
您的条件陈述是错误的。试试这个。
:conditions =&gt; ['transactions.datasource = accounts.datasource']