Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails build association from the polymorphic belongs_to object

I have a polymorphic relation as follows:

class Profile
  belongs_to :practice, polymorphic: :true
end

class ForeclosurePractice
  has_one :profile, as: :practice
end  

I want to build a practice object based on the profile I have, but unfortunately practice returns nil:

p = Profile.new
p.practice # => nil

How can I build the practice object from the Profile object?

like image 907
Donato Avatar asked Oct 18 '25 11:10

Donato


1 Answers

p.build_practice won't work, because the build_other method is not generated for polymorphic associations.

If you want a way to dynamically create an instance, for example based on a class name selected in a form, you can try to use safe_constantize - simple example:

p.practice = params[:practice_type].safe_constantize.new
like image 175
Matt Avatar answered Oct 20 '25 02:10

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!