【问题标题】:rails 4 has_one nested forms not building stillrails 4 has_one 嵌套表单仍未构建
【发布时间】:2016-01-10 03:24:24
【问题描述】:

我已经查看了有关 stackoverflow 和其他地方的这个相当常见问题的所有帖子,但我还没有找到答案。基本上我的嵌套表单没有构建,因此在我显示页面时不可见。

这是我的用户控制器的相关部分,users_controller.rb

  def new
    @user = User.new
    @user.build_user_account
  end

这是我的user.rb 文件中的相关部分:

class User < ActiveRecord::Base
      has_one :user_account, :class_name => "UserAccount"
      accepts_nested_attributes_for :user_account

还有我的user_account.rb 文件:

    class UserAccount < ActiveRecord::Base
      belongs_to :user
    end

这是我的_form.html.erb 文件:

<div class="field">
  <%= f.label :email %><br>
  <%= f.text_field :email %>
</div>
<div class="field">
  <%= f.label :password %><br>
<%= f.text_field :password %>
</div>
<div class="field">
  <%= f.label :password_confirmation %><br>
  <%= f.text_field :password_confirmation %>
</div>
<% f.fields_for :user_account, @user.user_account do |user_account| %> 
  <div class="field">
    <%= user_account.label :email %>
    <%= user_account.text_field :email %>
  </div>
  <div class="field">
    <%= user_account.label :password %>
    <%= user_account.text_field :password %>
  </div>
  <div class="field">
    <%= user_account.label :password_confirmation %>
    <%= user_account.text_field :password_confirmation %>
  </div>
<% end %> 

前三个按预期显示,但user_account 的三个表单字段未显示。我已经尝试了所有可以在网上找到的方法,但我仍然无法找出问题所在 - 不胜感激!

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 nested-forms has-one


    【解决方案1】:

    我认为您刚刚错过了f.fields_for 行中的= 符号。试试这样:

    <%= f.fields_for :user_account, @user.user_account do |user_account| %>
    

    @user.user_account 也不是必需的,但不会造成伤害。

    【讨论】:

    • 天哪,你是对的,它现在可以工作了!非常感谢!
    • 您也不需要为您的 user_account 关联声明 class_name
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多