Using :joins in Ruby on Rails 3
Greetings I have 3 db tables:
Types id name
Sources id name type_id
Operations id source_id comment ...
and models for each:
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
In Operation#index controller i have code for getting data (generated by scaffolding)
@operations = Operation.all
And piece of view operations/index.html.erb also generated by scaffolding
<% @operations.each do |operation| %>
<tr>
<td><%= operation.source_id %></td>
<td><%= operation.comment %></td>
</tr>
<% end %>
Now I want to use source.name instead of *operation.source_id*
I tried to do:
-replace operation.source_id to operation.sources.name # doesn't work
-tried to using :joins, and can't get Sources table fields
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>
or
irb(main):063:0> Operation.first( :joins => 'INNER JOIN sources ON operations.sourc开发者_运维知识库e_id = sources.id' )
=> #<Operation id: 2088, source_id: 1, summ: 10.0, comment: "", created_at: "2011-01-01 07:39:45", updated_at: nil>
How I must properly use :joins for get additional field? Or there is another approach to get combined tables data.
And why in the operations/show.html.erb i can use <%= @operation.source.name %> and successfully get source.name, but in the *operations/index.html.er*b can't
<% @operations.each do |operation| %>
<tr>
<td><%= operation.source.name %></td>
<td><%= operation.comment %></td>
</tr>
<% end %>
I'd also recommend changing your #index
method to use an includes
statement to avoid an N+1 situation (i.e. running a separate database query for each individual operation's source).
@operations = Operation.includes(:source).all
Solved:
opearions#index
@operations = Operation.all :joins => :source, :select => '*'
operations/index.html.erb
<% @operations.each do |operation| %>
<tr>
<td><%= operation.name %></td>
...
精彩评论