0

I've reread the rails guide to associations but still am hitting my head up against the wall. I've seen some advanced questions on Stack Overflow and am not able to determine if they shed light on my problem. Perhaps I've haven't gotten my mind wrapped around this. Please show me what I'm not seeing.

I have a School.rb which has_many Events, has_many Venues. Each of the Events and Venues belongs_to School. I'm trying to link up the Venue to an Event. They are tied to the school because they have a matching school_id. The name of the school is easily applied in Event#show and Venue#show as expected. The trick is how do I craft the Event controller to use the school_id to pull the Venue's addy in the Event#show page?

My attempts keep missing so I got to thinking maybe I have to make the Event belongs_to Venue and Venue has_many Events. Is that the right thing to do?

I attempt <%= @event.venue.address %> but that fails with 'undefined method `address' for nil:NilClass'

Maybe I'm overthinking it but as I mention above, I don't know enough to ask the right question. If I was to put my query in English terms it would be "Grab the instance of Venue whose school_id matches the school_id of the current/active Event." Does that make sense? I've attempted to find something close to that in the rails guides and attempted this:

 @venues = Venue.where(:school_id => @school_id)

undefined method `address' for []:ActiveRecord::Relation. The venue address is in the venue model.

Here's my school.rb:

 class School < ActiveRecord::Base

  has_many :events, :dependent => :destroy   
 has_many :venues, :dependent => :destroy
 has_and_belongs_to_many :users
  belongs_to :event   belongs_to :venue
  def self.fetch_for_name(_name)
 school = self.new(:name => _name)
  end 
 end

Here's my event.rb:

class Event < ActiveRecord::Base

resourcify
belongs_to :school
 belongs_to :venue
 end

Here's my Venue.rb:

 class Venue < ActiveRecord::Base

  resourcify
  belongs_to :school
   has_many :events

   end

Please help me get over this baby step, sam

4

2 に答える 2

0

求めていることを正確に行うには、Venueにメソッドを作成して、特定のイベントを照会します。

class Venue < ActiveRecord::Base
  resourcify
  belongs_to :school
  has_many :events
  def self.venue_for_event(event)
    where("school_id = ?", event.school_id)
  end
end

ただし、モデルについて尋ねられる質問がいくつかあります。なぜ学校には多くのイベントや会場がありますが、1つのイベントや会場にも属しているのですか?これらのモデルで解決しようとしている問題は何ですか?学校が会場とイベントを一緒に開催する接着剤である場合は、それをhas_many, :throughリレーションシップの参加モデルにすることを検討してください

于 2012-07-05T19:49:33.820 に答える
0

ガイドのこの部分を見て 、リンクで説明されているように、会場とイベントの間の関係を通じて has_many があることを確認する必要があります...

于 2012-07-05T19:24:23.630 に答える