简体   繁体   中英

Rails 4 - Polymorphic Association - Nested Attributes not showing in form

I am building a login system that has two users, buyer and seller, in Rails 4.0.4.

For auth I am using the Devise gem: https://github.com/plataformatec/devise

To create a new buyer I use the route buyer/new. However, the fields for the user do not show in the view. I also using debug to show @buyer.user in the view and it has been created. But when I call f.fields_for @buyer.user do |u| the loop is never entered.

Any ideas of why this is? Also, the polymorphic associations seem to be working in the rails console.

Buyer Controller:

  # GET /buyers/new
  def new
    @buyer = Buyer.new
    @buyer.build_user
  end

Buyer Model

class Buyer < ActiveRecord::Base
  has_one :user, as: :role
  accepts_nested_attributes_for :user
end

Buyer/new View

<%= form_for(@buyer) do |f| %>
  ....
  <div class="field">
    <%= debug(@buyer.user)  %>
    <% f.fields_for @buyer.user do |u| %>
      <%= u.text_field :email %>
    <% end %>
  </div>

User Model

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  belongs_to :role, polymorphic: true

Shouldn't you have an = on the fields_for? http://rubydoc.info/docs/rails/ActionView/Helpers/FormHelper:fields_for

EG

<%= f.fields_for @buyer.user do |u| %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM