这些是我的模型
class Apartment
belongs_to :house
end
class House
has_many :apartments
end
apartment_controller;
def index
@apartments = Appartment.all
end
公寓索引视图
.span9
#container
- @appartments.each do |apartment|
.item{:class => apartment.features_to_html_class }
%article.info.t_xs
.article-base
%section
.span3
%h2 #{link_to apartment.name, appartment_path(apartment)}
%p
= raw truncate(apartment.property_description, :length => 375, :omission => '...')
%footer
%ul.meta
%li.comments
#{apartment.count_ratings}
= t('apartment.details.reviews')
%li.notes
#{apartment.guests}
= t('apartment.details.persons')
%li.notes
#{apartment.bedrooms}
= t('apartment.details.bedrooms')
%li.notes
#{apartment.bathrooms}
= t('apartment.details.bathrooms')
%ul.thumbnails
%li.span5
= image_tag(apartment.attachments.last.file.url, :class => 'thumbnail')
- apartment.attachments.limit(4).each do |a|
%li.span1
%a{:href => "#"}
= image_tag(a.file.url(:thumb), :class => "thumbnail")
.span8
%footer
#more
#{link_to t('apartments.summary.button'), appartment_path(apartment), :class => 'btn btn-primary'}
我从DB得到所有的公寓。但是现在我想在公寓摘要中添加一个指向房屋的链接(belongs_to)。我该怎么做...谢谢。。雷姆科
你试过吗 link_to "房子",house_path(公寓.房子) ?
试试这个:
<%= link_to 'House', house_path(apartment.house) %>
或
<%= link_to 'House', house_url(apartment.house) %>
问候!
你得到了数据库中的所有公寓。现在,运行 sql 以获取apartments
对象。
然后迭代每个公寓,并通过关联将其链接到房屋。
这是按如下方式完成的:
def index
@apartments = Appartment.all
@apartments.each do |apartment|
#this is giving you the link to house via association defined.
apartment.house
#this is giving you the value of the field say `house_name` of house table that is linked to apartment.
@house_name = apartment.house.house_name
.
.
.
end
end