在 Rails 上使用 Ruby 中的关联
Using associations in Ruby on Rails
我正在学习 RoR,我正在尝试理解关联。我有两个模型——Company [name] 和 Note [company_id, notes]。如图所示,Note 模型有一个 company_id 字段来引用 Company 模型中的主键。
在 Notes 视图中,我试图显示公司名称,但似乎无法正常工作。
我要展示
(SELECT name FROM Company WHERE Company.id=Note.company_id)
而不是下面代码中的 note.company_id。
company.rb
class Company < ActiveRecord::Base
has_many :notes
end
note.rb:
class Note < ActiveRecord::Base
belongs_to :company
default_scope -> { order(date: :desc) }
end
notes/index.html.erb
....
<% @notes.each do |note| %>
<% if note.active %>
<p>
<%= note.date %>
</br>
<%= note.company_id %> - <%= note.contact %>
</br>
<%= note.notes %>
<!-- <td><%= note.active %></td> -->
</p>
<% end %>
<% end %>
....
要回答您的具体问题,请尝试:
note.company.name
我还建议阅读 Rails 部分,特别是如何呈现集合:http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials
我正在学习 RoR,我正在尝试理解关联。我有两个模型——Company [name] 和 Note [company_id, notes]。如图所示,Note 模型有一个 company_id 字段来引用 Company 模型中的主键。
在 Notes 视图中,我试图显示公司名称,但似乎无法正常工作。
我要展示
(SELECT name FROM Company WHERE Company.id=Note.company_id)
而不是下面代码中的 note.company_id。
company.rb
class Company < ActiveRecord::Base
has_many :notes
end
note.rb:
class Note < ActiveRecord::Base
belongs_to :company
default_scope -> { order(date: :desc) }
end
notes/index.html.erb
....
<% @notes.each do |note| %>
<% if note.active %>
<p>
<%= note.date %>
</br>
<%= note.company_id %> - <%= note.contact %>
</br>
<%= note.notes %>
<!-- <td><%= note.active %></td> -->
</p>
<% end %>
<% end %>
....
要回答您的具体问题,请尝试:
note.company.name
我还建议阅读 Rails 部分,特别是如何呈现集合:http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials