通过四种模式有关系吗?

时间:2010-12-28 04:23:02

标签: ruby-on-rails model associations

我在模型之间设置此关联时遇到了问题。

用户有很多住宿,住宿有一个用户。

住宿有很多通知,而通知有一个住宿。

请求有很多通知。

如何才能使我能够获得给定用户的所有请求(即用户 - >住宿(每个) - >通知 - >请求)?

更新

这是我当前的控制器文件:

class PanelController < ApplicationController

  before_filter :login_required

  def index
    @accommodations = current_user.accommodations.all
    @requests = Array.new
    @accommodations.each do |a|
      a.notifications.each do |n|
        @requests << Request.where('id' => n.request_id)
      end
    end

  end

end

模特:

模型/ user.rb

class User < ActiveRecord::Base
  [snip]
  has_many :accommodations
  has_many :notifications,
           :through => :accommodations
end

模型/ accommodation.rb

class Accommodation < ActiveRecord::Base
  validates_presence_of :title, :description, :thing, :location, :spaces, :price, :photo
  attr_accessible :photo_attributes, :title, :description, :thing, :location, :spaces, :price
  has_one :photo
  has_many :notifications
  belongs_to :user
  accepts_nested_attributes_for :photo, :allow_destroy => true
end

模型/ notification.rb里

class Notification < ActiveRecord::Base
  attr_accessible :accommodation_id, :request_id
  has_one :request
  belongs_to :accommodation
end

模型/ request.rb

class Request < ActiveRecord::Base
  belongs_to :notifications
  attr_accessible :firstname, :lastname, :email, :phone, :datestart, :dateend, :adults, :children, :location, :status
  validates_presence_of :firstname, :lastname, :email, :phone, :datestart, :dateend, :children, :adults, :location
end

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

@reqs = []    
@user.accommodations.all.each do |a|
    @reqs << a.notification.request
end

假设这是正确的:

class User
    has_many :accommodations
end

class Accommodation
    belongs_to :user
    has_many :notifications
end

class Notification
    belongs_to :accomodation
    belongs_to :request
end

class Request
    has_many :notifications
end

使用has_many :through不适用于多个模型,如下所示:Ruby-on-Rails: Multiple has_many :through possible?

但是你可以在你的用户模型中做这样的事情:

class User
    has_many :accommodations
    has_many :notifications,
             :through => :accommodations

    def requests 
        self.notifications.all.collect{|n| n.request }
    end
end