0

我要做的是编写一个方法,该方法将返回该模型的所有 outing_locations,它与它有一个 has_many 关系。

class Outing < ActiveRecord::Base
  attr_accessible :description, :end_time, :start_time, :title, :user_id

  belongs_to :user
  has_many :outing_locations
  has_many :outing_guests
  has_one :time_range, :foreign_key => "element_id", :conditions => { :element_type => "outing" }

  validates :title, :presence => true
  validates :start_time, :presence => true # regex
  validates :end_time, :presence => true # regex

  def host_name
    return User.find(self.user_id).full_name
  end


end

我正试图让这个块特别工作。

还有另一个名为 OutingInvite 的模型,其中包含特定 Outing 的 id。我需要使用它来获取正确的郊游,然后拉出所述郊游的相关郊游地点。

这是一个粗略的示例:

<%@outing_invites.each do |invite|%>
 ...
    <% @party = Outing.where(:id => invite.outing_id) %>
    <% @party.outing_locations.each do |location| %>

然后让它输出每个位置。

但是,它说方法'outing_locations'不存在......

4

1 回答 1

2

model_instance.associated_model_name.您可以通过在示例中输入 So 来查看模型的关联模型,即outinghas_many outing_locations。在你拥有一个 的实例之后,outing比如说@o = Outing.find(1)使用o.outing_locationsouting_locationsouting.

请参阅Ruby on Rails 指南中的此示例

编辑

您收到method 'outing_locations' does not exist错误的原因是因为Outing.where(:id => invite.outing_id)返回一个数组,并且没有outing_locations数组方法。您需要获取特定实例(如 with Outing.find(invite.outing_id)或使用该数组中的特定索引。我建议使用Outing.find(invite.outing_id)因为(我假设)你的每个 Outing 都有一个唯一的 ID。

于 2012-06-26T23:58:25.350 回答