【问题标题】:nested forms not working with has_one association and fields_for嵌套表单不适用于 has_one 关联和 fields_for
【发布时间】:2016-03-02 03:56:02
【问题描述】:

我有 2 个模型:

class Buyer < ActiveRecord::Base
  has_one :buyer_info
  accepts_nested_attributes_for :buyer_info
end

型号BuyerInfo

class BuyerInfo < ActiveRecord::Base
  belongs_to :buyer
end

在控制器中(我使用设计创建买家/buyers/registrations_controller

class Buyers::RegistrationsController < Devise::RegistrationsController
  def new
    super
    resource.build_buyer_info
  end
end

在_form registrations/_form

<div class="">
  <div class="mid">
    <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
      <%= f.text_field :full_name, :placeholder => "YOUR NAME", :class => "form-control"%>
      <%= f.text_field :email, :placeholder => "EMAIL ADDRESS", :class => "form-control", :class => "form-control"%>
      <%= f.text_field :phone, :placeholder => "PHONE NUMBER", :class => "form-control"%>
      <br/> <br/>

      <%= f.fields_for :buyer_info do |buyer_info| %>
        <%= buyer_info.text_field :email_receive1, :placeholder => "SEND MY LEADS TO EMAIL #1 ", :class => "form-control"%>
        <%= buyer_info.text_field :email_receive2, :placeholder => "SEND MY LEADS TO EMAIL #2 ", :class => "form-control"%>
        <%= buyer_info.text_field :email_receive3, :placeholder => "SEND MY LEADS TO EMAIL #3 ", :class => "form-control"%>
        <%= buyer_info.text_field :email_receive4, :placeholder => "SEND MY LEADS TO EMAIL #4 ", :class => "form-control"%>  
      <% end %>
      <%= f.submit "Comment", :type => :image, :src => "#{asset_url(@source_folder+'signup-button.png')}" %>

    <% end %>       
  </div>           
</div>  

当我运行代码时,视图中只显示 text_fields full_name、email、phone。它不会在 fields_for 中显示字段。

当创建的模型使用嵌套模型has_one关系时如何在fields_for中显示字段?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 devise rubygems


    【解决方案1】:
    class Buyers::RegistrationsController < Devise::RegistrationsController
      def new
        build_resource({})
        @buyer_info = resource.build_buyer_info
      end
    end
    

    试试这个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-08
      • 2021-04-06
      • 1970-01-01
      相关资源
      最近更新 更多