【发布时间】:2011-01-26 23:21:04
【问题描述】:
问候 我有 3 个数据库表:
类型 ID 名字
来源 ID 姓名 type_id
运营 ID source_id 评论 ...
和每个模型:
class Type < ActiveRecord::Base
has_many :sources, :dependent => :destroy
end
class Source < ActiveRecord::Base
belongs_to :type
has_many :operations, :dependent => :destroy
end
class Operation < ActiveRecord::Base
belongs_to :source
default_scope :order => 'created_at DESC'
end
在 Operation#index 控制器中,我有获取数据的代码(由脚手架生成)
@operations = Operation.all
还有一块视图operations/index.html.erb也是脚手架生成的
<% @operations.each do |operation| %>
<tr>
<td><%= operation.source_id %></td>
<td><%= operation.comment %></td>
</tr>
<% end %>
现在我想使用 source.name 而不是 *operation.source_id*
我尝试过:
-将 operation.source_id 替换为 operation.sources.name # 不起作用
-尝试使用 :joins,但无法获取 Sources 表字段
irb(main):057:0> Operation.first( :joins => :source )
=> #<Operation id: 2088, source_id: 1, summ: 10.0, comment: "", created_at: "2011-01-01 07:39:45", updated_at: nil>
或
irb(main):063:0> Operation.first( :joins => 'INNER JOIN sources ON operations.source_id = sources.id' )
=> #<Operation id: 2088, source_id: 1, summ: 10.0, comment: "", created_at: "2011-01-01 07:39:45", updated_at: nil>
我必须如何正确使用 :joins 来获取附加字段? 或者还有另一种获取组合表数据的方法。
以及为什么在 operations/show.html.erb 中我可以使用 并成功获取 source。名称,但在*operations/index.html.er*b 中不能
【问题讨论】:
标签: ruby-on-rails-3 activerecord join