Rails creates an association from object polyorphic belongs to_object
I have a polymorphic relationship like this:
class Profile
belongs_to :practice, polymorphic: :true
end
class ForeclosurePractice
has_one :profile, as: :practice
end
I want to create a practice object based on a profile I have, but unfortunately the command returns nil:
p = Profile.new
p.practice # => nil
How can I create a practice object from a Profile object?
+3
source to share
2 answers
p.build_practice
won't work because build_other method is not generated for polymorphic associations .
If you need a way to dynamically instantiate, for example based on the class name selected in the form, you can try using save_constantize - a simple example:
p.practice = params[:practice_type].safe_constantize.new
+2
source to share
You need to explicitly create the association:
p = Profile.new p.build_practice
See: http://apidock.com/rails/v4.0.2/ActiveRecord/Associations/ClassMethods/belongs_to
0
source to share