你想要做的就是所谓的“嵌套模型”。
首先,您必须告诉模型允许其他模型是这样的:
# app/model/user.rb
class User < ActiveRecord::Base
belongs_to :role
accepts_nested_attributes_for :role
end
下一件事在你看来
#app/views/users/new.html.ham
= simple_form_for @user do |f|
= f.input :name
= f.input :email
%br
= f.simple_fields_for :role do |role|
= role.input :designer
= role.input :developer
= f.button :submit, "Send Message", :class => 'btn btn-primary btn-block'
现在最后但最不重要的是你能够接受控制器中的新参数
class UsersController < ApplicationController
expose(:users){User.all.order(:id)}
expose(:user, attributes: :user_params)
def new
@user = User.new
@user.role.build
end
def create
if user.save
flash[:notice] = t(:user_was_successfully_created)
redirect_to root_path
else
render :new
end
end
private
def user_params
params.require(:user).permit(
[
:email ,
:name ,
role_attributes: [
:designer,
:developer,
]
]
)
end
end
您可以查看示例应用程序https://github.com/mzaragoza/sample_nestes_forms
我希望这有助于快乐黑客