can I use an attribute value to set up a has_one association? This is what I''ve tried so far : class Archive < ActiveRecord::Base has_one :document, :class_name => "#{doc_type}" end doc_type is an column in the ''archives'' table, but here''s the error I get : undefined local variable or method `doc_type'' for Archive:Class is it possible to do what I''m trying here? thanks alan
I''m not sure if it is possible as I haven''t done it, but you''ll probably need to change the " to '' as in: has_one :document, :class_name => ''#{doc_type}'' The " causes ruby to immediately try and find the doc_type variable, which it can''t do as it''s just setting up the class. The '' doesn''t try and do any escaping, so the string will be passed through as is and hopefully AR will find the attribute then. HTH, Chris On 4/18/05, Alan Bullock <liststuff-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> can I use an attribute value to set up a has_one association? > This is what I''ve tried so far : > > class Archive < ActiveRecord::Base > has_one :document, :class_name => "#{doc_type}" > end > > doc_type is an column in the ''archives'' table, but here''s the error I get : > undefined local variable or method `doc_type'' for Archive:Class > > is it possible to do what I''m trying here? > thanks > > alan > _______________________________________________ > Rails mailing list > Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org > http://lists.rubyonrails.org/mailman/listinfo/rails >
On 4/19/05, Alan Bullock <liststuff-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> can I use an attribute value to set up a has_one association? > This is what I''ve tried so far : > > class Archive < ActiveRecord::Base > has_one :document, :class_name => "#{doc_type}" > end > > doc_type is an column in the ''archives'' table, but here''s the error I get : > undefined local variable or method `doc_type'' for Archive:ClassI don''t believe this is possible, if someone else can help you get it working, then cool.> is it possible to do what I''m trying here?What is the actual problem you''re trying to solve, perhaps there''s a simpler way that fits more comfortably with ActiveRecord''s approach. An archive has a document, but the document can be of any type? Why do you have seperate classes for the document, is there different behaviour in the different documents? Could you model this as follows? class Archive < ActiveRecord::Base has_one :document end class Document < ActiveRecord::Base belongs_to :document_type end class DocumentType < ActiveRecord::Base end> thanks > > alan > _______________________________________________ > Rails mailing list > Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org > http://lists.rubyonrails.org/mailman/listinfo/rails >-- Cheers Koz