0

场景是 u 用户 has_many head_bookings 和 head_bookings has_many 预订并且公寓属于预订。head_booking 有一个订单号。因此,当用户登录时,他们会通过 head_booking(订单号)获得公寓组的预订

这是我的模型

    class User < ActiveRecord::Base
      has_many :head_bookings
    end



class HeadBooking < ActiveRecord::Base

    has_many :bookings  
    belongs_to :user
  # attr_accessible :title, :body
end

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

end

我在表中创建了一些虚拟数据,并在控制台中尝试了这个:

u = User.find(1)
u.head_bookings
u.head_bookings.bookings

使用命令 u.head_bookings.bookings 我得到错误“未定义的方法 `bookings'”

我究竟做错了什么??谢谢..remco

4

3 回答 3

1

您可以将预订与用户相关联。

class User < ActiveRecord::Base
  has_many :head_bookings
  has_many :bookings, through: :head_bookings
end

然后您可以通过以下方式选择用户的预订:

u = User.find(1)
u.bookings
于 2013-09-09T13:54:33.077 回答
1

如果您计划直接处理用户的预订,则应在UserBookingusing之间添加关系has_many through

class User < ActiveRecord::Base
  has_many :head_bookings
  has_many :bookings, through: :head_bookings
end

这将允许您执行诸如u.bookings获取通过他的头部预订加入的用户的所有预订之类的事情。

于 2013-09-09T13:54:49.310 回答
0

从那时User has_many :head_bookings起,当您执行 a 时u.head_bookings,它会返回一个关系(充当数组),并且您不能.bookings在数组中执行 a 。

尝试类似的东西

u.head_bookings.each do |hb|
  b.bookings
end

要使用bookings每个head_booking.

于 2013-09-09T13:48:14.250 回答