我是rails社区的新手。我正在开发一个应用程序,用户可以使用名字和名字的嵌套属性的用户名。与User模型关联的其他文本字段工作正常。
非常感谢任何帮助。
附带应用程序模型,控制器,迁移文件,数据库架构和视图。
模型
class User < ActiveRecord::Base
has_one :username, dependent: :destroy
accepts_nested_attributes_for :username, allow_destroy: true
end
class Username < ActiveRecord::Base
belongs_to :user
end
迁移
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email
t.string :about_me
t.string :nationality
t.string :sexe
t.timestamps null: false
end
end
end
class CreateUsernames < ActiveRecord::Migration
def change
create_table :usernames do |t|
add_column :username, :first_name, :string
add_column :username, :last_name, :string
t.references :user, index: true, foreign_key: true
t.timestamps null: false
end
end
end
控制器
class UsersController < ApplicationController
def index
@all_users = User.all
@new_user = User.new
@username = Username.new
end
def new
@new_user = User.new
end
def create
User.create(user_params)
end
private
def user_params
params.require(:user).permit(:email, :about_me, username_attributes:
[:last_name, :first_name])
end
end
视图
<h1>Users#index</h1>
<p>Find me in app/views/users/index.html.erb</p>
<%= form_for @new_user do |f| %>
<%= f.fields_for @new_user do |user| %>
<div class="field">
<%= user.label :email%>
<%= user.text_field :email %>
<%= user.label :about_me %>
<%= user.text_field :about_me %>
</div>
<% end %>
<%= f.fields_for :username do |name| %>
<div class="field">
<%= name.label :first_name %>
<%= name.text_field :first_name %>
</div>
<% end %>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
答案 0 :(得分:0)
试试这个 控制器
def new
@new_user = User.new
@new_user.usernames.build
end
视图
<%= form_for @new_user do |f| %>
# ...
<%= f.fields_for :usernames do |name| %>
<div class="field">
<%= name.label :first_name %>
<%= name.text_field :first_name %>
</div>
<% end %>
# ...
<% end %>
辅助
def name_format(user_mst)
name = user_mst.first_name.capitalize
name += (" #{user_mst.last_name.capitalize}")
return name
end
在视图上显示