简体   繁体   English

owners_添加关系?

[英]belongs_to add a relationship?

these are my models 这些是我的模特

class Apartment
belongs_to :house
end

class House
has_many :apartments
end

apartment_controller; apartment_controller;

def index
    @apartments = Appartment.all
end

apartment index view 公寓索引视图

.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'}

i get all the apartments from the DB. 我从数据库获得所有公寓。 But now i want to add a link (belongs_to) to the house in at the apartment summary. 但是现在我想在公寓摘要中添加到房屋的链接(belongs_to)。 how can i do this...thanks..remco 我该怎么办...谢谢..remco

您是否尝试过link_to“房屋”,house_path(apartment.house)?

Try this: 尝试这个:

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

or 要么

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

Regards! 问候!

You got all the apartments in the database. 您已在数据库中获得所有公寓。 Now you run the sql to get the apartments object. 现在,您运行sql来获取apartments对象。
Then iterate each apartment and link it to house with the association. 然后迭代每个公寓,并将其链接到具有关联的房屋。

This is done as follows: 这样做如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM