我有一个很好的关系。这些是模型
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(db记录),我想显示公寓的名称。
谢谢.. REMCO
答案 0 :(得分: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.