建模双有很多通过

时间:2016-03-09 02:37:05

标签: ruby-on-rails activerecord rails-activerecord

我正在运行我有4个模型的项目,分别是:客人,主人,房间,预订。

# host.rb
has_many :rooms

# room.rb
belongs_to :host
has_many :reservations
has_many :guests, through: :reservations

# reservation.rb
belongs_to :guest
belongs_to :room

# guest.rb
has_many :reservations
has_many :rooms, through: :reservations

我可以使用以下代码在客人中预订房间和预订:

# reservations_controller.rb
def your_trips
  @trips = current_guest.reservations
end

# your_trips.html.erb
<% @trips.each do |trip %>
  <%= trip.room.room_name %>
<% end %>

然而,我无法致电在主持人中预订的客人。我怎样才能做到这一点?我相信活跃的唱片协会中缺少一些东西,但我不知道是什么。

更新1

我添加了主机的预订列表,这是代码:

# rooms_controller.rb
def reservation_list
  @rooms = current_host.rooms
  @reservedguests = @rooms.guests(params[:id])
end

# reservation_list.html.erb
<% @reservedguests.each do |reservedguest| %>
  <%= reservedguest.full_name %>
<% end %>

它给了我这个错误:

NoMethodError in RoomsController#reservation_list
undefined method `guests' for #<Job::ActiveRecord_Associations_CollectionProxy:0x007f8c69e65eb8>

但是,当我尝试在rails console中执行此命令时:

> @host = Host.find(1)
> @room = @host.room.find(1)
> @reservation = @room.reservation.find(1)
> @reservedguest = @reservation.guests.find(1)
> @reservedguest.full_name
=> "My name here"

这意味着它应该正常工作。我错过了什么?

更新2

我通过替换这些行尝试了@potashin:

#rooms_controller.rb    
def reservation_list
  @rooms = current_host.rooms
  @reservedguests = Guest.find_by(room_id: @rooms.pluck(:id), id: params[:id])
end

但是,它给了我另一个错误:

ActiveRecord::StatementInvalid in RoomsController#reservation_list
PG::UndefinedColumn: ERROR: column guests.room_id does not exist LINE 1: SELECT "guests".* FROM "guests" WHERE "guests"."room_i... ^ : SELECT "guests".* FROM "guests" WHERE "guests"."room_id" IN (2, 1) AND "guests"."id" IS NULL LIMIT 1

这是什么意思?

1 个答案:

答案 0 :(得分:1)

@rooms是一个数组。 #guests适用于单个会议室。您有几个选择:

选项1

@reservedguests = @rooms.map(&:guests).flatten

选项2 (追加)

如果你想真正想要,或者想要看到所有主持人的客人:

<强>模型

class Host
  has_many :guests, through: :rooms

<强>控制器

@reserved_guests = current_host.guests