1

我有一个 has_many through 关系。这些是模型

class User < ActiveRecord::Base
  has_many :bookings
  has_many :apartments, through: :bookings

end

class Apartment < ActiveRecord::Base
 has_many :bookings
 has_many :users, through: :bookings
end


class Booking < ActiveRecord::Base
  # attr_accessible :title, :body
  belongs_to :user
  belongs_to :appartment

end

表结构:

def change
    create_table :bookings do |t|
      t.integer :appartment_id, :null => false
      t.integer :user_id, :null => false
      t.datetime :booking_date 
      t.timestamps
    end
   end

显示用户视图

- @user.bookings.each do |booking|
                %ul
                  %li
                    Refnr.:
                    = booking.ref

如何将指向公寓的链接(名称属性)添加到每个循环?

我试过了

= booking.apartment_id

但我得到了 ID(数据库记录),我想显示公寓的名称。

谢谢..remco

4

1 回答 1

2

如果要打印与预订相关的公寓名称,可以试试这个:

= booking.apartment.name # If you are sure, each booking is having apartment associated with it.

= booking.apartment.try(:name) # Else you should handle the exception also.
于 2013-09-06T16:09:51.637 回答