Conditional statements in association model in Rails
Using Rails 2.3.8. I have the following in my view:
<% if !@shop.city_shops.blank? %>
<% @shop.city_shops.each do |city_shop| %>
<% if !city_shop.notes.blank? %>
<% city_shop.notes %>
<% else %>
<p>No notes.</p>
<% end %>
<% end %>
<% else %>
<p>No notes.</p>
<% end %>
city_shops
has a database column called notes
; bel开发者_开发技巧ongs_to
shop
.
shop
has_many
city_shops
.
In article A
, I add a shop with ID 50
into a new row city_shop
, and add notes
.
In article B
, I add a shop with ID 50
into a new row city_shop
, and no notes.
In article C
, I add a shop with ID 51
into a new row city_shop
, and no notes.
Result of city_shop
database:
ID | shop_id | notes
1 | 50 | Test
2 | 50 |
3 | 51 |
In view.html.erb
of shop 50
, I want to show the notes Test
from city_shop
ID 1.
In view.html.erb
of shop 51
, I want to show the No notes
from city_shop
ID 3.
Thank you.
<% no_notes = false %>
<% @shop.city_shops.each do |city_shop| %>
<% unless city_shop.notes.blank? %>
<% city_shop.notes %>
<% else %>
<% no_notes = true %>
<% end %>
<% end %>
<% if no_notes %>
<p>No notes.</p>
<% end %>
精彩评论