belongs_to添加关系?

时间:2013-01-23 13:25:31

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

这些是我的模特

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)到房子。我怎么能这样做...谢谢......很高兴

3 个答案:

答案 0 :(得分:1)

你尝试过吗?    link_to'House',house_path(apartment.house)?

答案 1 :(得分:1)

试试这个:

<%= link_to 'House', house_path(apartment.house) %> 

<%= link_to 'House', house_url(apartment.house) %>

问候!

答案 2 :(得分:0)

你拥有数据库中的所有公寓。 现在运行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