has_many :through not giving access to <class>_id from base
Model code
class Location < ActiveRecord::Base
attr_accessible :day_tokens, :name, :address, :phone
has_many :locavailability
has_many :dayavailables, :through => :locavailability
attr_reader :day_tokens
def day_tokens=(ids)
self.locavailability.dayavailable_id= ids.split(",")
end
end
class Dayavailable < ActiveRecord::Base
has_many :locavailability
has_many :locations, :through => :locavailability
end
class Locavailability < ActiveRecord::Base
attr_accessible :dayavailable_id, :location_id
belongs_to :dayavailable
belongs_to :location
end
Database Columns:
locations: id, name, address, phone, hours, created_at, updated_at
dayavailables: id, day, time, created_at, updated_at
locavailabilities: id, location_id, dayavailable_id, created_at, updated_at
Error
irb(main):004:0> l = Location.find(1)
=> #<Location id: 1, name: "test", address: "123 Fake Street", phone: "23443234324", hours: "M-F 9 - 5", created_at: "2011-05-16 04:56:31", updated_at: "2011-05-16 04:56:31">
irb(main):005:0> l.class
=> Location(id: integer, name: string, address: string, phone: string, hours: string, dentistry_id: integer, created_at: datetime, updated_at: datetime)
irb(main):006:0> l.locavailability
=> []
irb(main):007:0> l.dayavailable_id
NoMethodError: undefined method `dayavailable_id' for #<Location:0xb6af7c40>
from /usr/lib/ruby/gems/1.8/gems/activemodel-3.0.0/lib/active_model/attribute_methods.rb:364:in `method_missing'
from /usr/lib/ruby/gems/1.8/gems/activerecord-3.0.0/lib/active_record/attribute_methods.rb:46:in `method_missing'
from /usr/lib/ruby/gems/1.8/gems/activerecord-3.0.0/lib/active_record/attribute_methods.rb:44:in `send'
from /usr/lib/ruby/gems/1.8/gems/activerecord-3.0.0/lib/active_record/attribute_methods.rb:44:in `method_missing'
from (irb):6
Shouldn't Location class have access to dayavailable_id
?? I am going by the code in railscasts episode 258 on github开发者_如何学JAVA
What am I missing?
Why Location
should have access to dayavailable_id
?
The dayavailable_id
is column of locavailabilities
, if you given true:
Database Columns:
locations: id, name, address, phone, hours, created_at, updated_at
dayavailables: id, day, time, created_at, updated_at
locavailabilities: id, location_id, dayavailable_id, created_at, updated_at
Try this: UPDATED
l = Location.find(1)
l.dayavailable_ids #=> Returns an array of the associated objects’ ids
But if you call dayavailable_id
, it should be a column of table.
So l.dayavailable_ids
will execute this DB query:
select id from dayavailables d
inner join locavailabilities l on l.dayavailable_id = d.id
where l.location_id = 1
but Locavailability.find(1).dayavailable_id will execute this DB query(not really, only for more readable):
select dayavailable_id from locavailabilities l
where l.location_id = 1
精彩评论