Rails has_many assocation with non-class?
I would like to build a model where a class of ServiceRegions has a many-to-many relationship with zip codes. That is, ServiceRegions might cover multiple zip codes, and they might overlap, so the same zip code could be associated with multiple ServiceRegions.
I was hoping to store the zip code directly in a relationship table rather than creating a ZipCode class, but I can't get the code to work properly. I successfully got code to create relationships, but I was unable to access an array of associated zips as one would expect to be able to.
Here's the relevant code:
class ServiceRegion < ActiveRecord::Base
has_many :z_sr_relationships, :dependent => :destroy,
:foreign_key => :service_region_id
has_many :zips, :through => :z_sr_relationships, :source => :zip
def includes_zip!(zip)
z_sr_relationships.create!( :zip_id => zip, :service_region_id => self.id)
end
end
class ZSrRelationship < ActiveRecord::Base
attr_accessible :service_region_id, :zip
belongs_to :service_region, :class_name => "ServiceRegion"
validates :zip, :presence => true
validates :service_region_id, :presence => true
end
When I do a show on an instance of a ServiceRegion and try to outpu开发者_运维知识库t my_service_region.zips it gives me an error that it can't find the association zips.
Is Rails meant to let you do a many to many association with a basic type like a string or an int that's not a defined class with its own model file?
Any association: has_many, belongs_to, has_many :though etc., need to relate to subclasses of active record. Objects that aren't a descendent of AR wouldn't have the database backing to relate to AR objects.
I think you're getting the "can't find association" error because you're specifying :source => :zip. You'd need to have a class called Zip. You have a class called ZSrRelationship, which is what rails expects, so you should probably just leave the source option out.
精彩评论