簡體   English   中英

owners_添加關系?

[英]belongs_to add a relationship?

這些是我的模特

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

我從數據庫獲得所有公寓。 但是現在我想在公寓摘要中添加到房屋的鏈接(belongs_to)。 我該怎么辦...謝謝..remco

您是否嘗試過link_to“房屋”,house_path(apartment.house)?

嘗試這個:

<%= 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM