gpt4 book ai didi

ruby-on-rails - Rails has_many 与多个键关联

转载 作者:数据小太阳 更新时间:2023-10-29 08:54:20 26 4
gpt4 key购买 nike

我正在尝试改变遗留数据库的 rails 。每个表都有一个“数据源”列,该列是数据来源的 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 中完成此任务的正确方法是什么?

最佳答案

分解并定制 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'

关于ruby-on-rails - Rails has_many 与多个键关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5290894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com