型号代码
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
数据库列:
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
错误
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
Location类不应该访问dayavailable_id
吗??我正在按照github 上railscasts第258集的代码进行
我错过了什么?
为什么Location
应该访问dayavailable_id
?如果给定true,则dayavailable_id
是locavailabilities
的列:
数据库列:
位置:id,名称,地址,电话,小时,created_at,updated_at
可用日期:id,day,time,created_at,updated_at
本地可用性:id,location_id,dayavailable_id,created_at,updated_at
试试这个:更新
l = Location.find(1)
l.dayavailable_ids #=> Returns an array of the associated objects’ ids
但如果调用dayavailable_id
,它应该是表的一列。
因此l.dayavailable_ids
将执行此DB查询:
select id from dayavailables d
inner join locavailabilities l on l.dayavailable_id = d.id
where l.location_id = 1
但是Locability.find(1).dayavailable_id将执行这个DB查询(不是真的,只是为了更可读):
select dayavailable_id from locavailabilities l
where l.location_id = 1