Rails 4 个嵌套字段未在表单中显示
Rails 4 nested fields not displayed in form
我试图在注册表单中显示嵌套的一些 user.profile 嵌套字段 (first_name, last_name),但它们没有出现..
== CONTROLLER
controllers/users_controller.rb
class UsersController < ApplicationController
def new
@user = User.new
render partial: 'users/new_form_content', layout: false
end
def user_params
params.require(:user).permit(:email, :password, profile_attributes: [:first_name, :last_name])
end
...
end
== MODELS
models/user.rb
class User < ActiveRecord::Base
has_one :profile
accepts_nested_attributes_for :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
end
== VIEW
users/new_form_content.rb
<div>
...
<%= form_for @user, remote: true, ... do |f| %>
<%= f.fields_for :profile do |profile_form| %>
<%= profile_form.text_field :last_name %>
<%= profile_form.text_field :first_name %>
<% end %>
...
<%= f.text_field :email %>
<%= f.text_field :password %>
<%= f.text_field :password_confirmation %>
...
<% end %>
...
</div>
您还需要在新方法中创建一个新配置文件:
def new
@user = User.new
@user.profile = Profile.new
render partial: 'users/new_form_content', layout: false
end
我试图在注册表单中显示嵌套的一些 user.profile 嵌套字段 (first_name, last_name),但它们没有出现..
== CONTROLLER
controllers/users_controller.rb
class UsersController < ApplicationController
def new
@user = User.new
render partial: 'users/new_form_content', layout: false
end
def user_params
params.require(:user).permit(:email, :password, profile_attributes: [:first_name, :last_name])
end
...
end
== MODELS
models/user.rb
class User < ActiveRecord::Base
has_one :profile
accepts_nested_attributes_for :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
end
== VIEW
users/new_form_content.rb
<div>
...
<%= form_for @user, remote: true, ... do |f| %>
<%= f.fields_for :profile do |profile_form| %>
<%= profile_form.text_field :last_name %>
<%= profile_form.text_field :first_name %>
<% end %>
...
<%= f.text_field :email %>
<%= f.text_field :password %>
<%= f.text_field :password_confirmation %>
...
<% end %>
...
</div>
您还需要在新方法中创建一个新配置文件:
def new
@user = User.new
@user.profile = Profile.new
render partial: 'users/new_form_content', layout: false
end