Polymorphism and forms in Ruby on Rails

前端 未结 1 1481
醉话见心
醉话见心 2021-01-01 06:04

I\'ve been full of questions lately, but thanks to this awesome community, I\'m learning a ton.

I got all the help I needed with polymorphic associations earlier and

相关标签:
1条回答
  • 2021-01-01 06:36

    Before we go further, I did notice one issue - you do not need the t.references with the has_many side of the association. So you do not need it in the create_user model. What that does is it creates the phonable_id and the phoneable_type columns, you only need that in the polymorphic model.

    You are heading down the correct path with the fields_for approach. But in order to get that working, you need to tell the model how to handle those fields. You do that with the accepts_nested_attributes_for class method.

    class User < ActiveRecord::Base
      has_many :phones, :as => :phoneable
    
      accepts_nested_attributes_for :phones
    end
    

    and one minor thing, you will need to have the fields_for point to the exact name of the association

    - form_for @user do |user_form|
      - user_form.fields_for :phones do |phone|
    

    Instead of

    - form_for @user do |user_form|
      - user_form.fields_for :phone do |phone|
    

    and make sure you remove your stray %> erb tag :)

    More on accepts_nested_attributes_for: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

    I hope this helps!

    0 讨论(0)
提交回复
热议问题