多个关联中没有方法

时间:2013-09-09 13:43:10

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

场景是你的用户has_many head_bookings和head_bookings has_many预订,公寓属于预订。 head_booking有一个订单号。因此,当用户登录时,他们通过head_booking(ordernumber)

获得公寓组的预订

这是我的模特

    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我得到错误“未定义的方法`预订'”

我做错了什么? Thanks..remco

3 个答案:

答案 0 :(得分:1)

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

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

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

u = User.find(1)
u.bookings

答案 1 :(得分:1)

如果您打算直接使用用户的预订,则应使用UserBookinghas_many through之间添加关系:

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

这将允许您执行u.bookings之类的操作,这些操作将通过他的预订来获取用户加入的所有预订。

答案 2 :(得分:0)

从您的User has_many :head_bookings开始,当您执行u.head_bookings时,它会返回一个关系(这种关系充当数组),而您无法执行.bookings在数组中。

尝试类似

的内容
u.head_bookings.each do |hb|
  b.bookings
end

使用每个bookings的{​​{1}}。