一、什么是嵌套表单呢?
举个简单的例子吧,比如你有两个表,一个User表,另一个Profile表,他们是一对一的关系(也可以一对多等)。现在需要提交一个表单的时候同时提交User,Profile对应的字段数据。在Rails中有一种简单的方法解决,分别使用了这些方法
accepts_nested_attributes_for
attr_accessible
fields_for
下面我们用代码进行说明一下。针对模型关系是一对一
class User < ActiveRecord::Base
has_one :profile, dependent: :destroy
accepts_nested_attributes_for :profile #注意添加这两行
attr_accessible :profile_attributes #如果user_parms指定了,可以不加这行
end
class Profile<ActiveRecord::Base
belongs_to :user
end
class UsersController < ApplicationController
def new
@user = User.new
@user.build_profile #不要遗漏,需要区别于一对多的情况
end
def create
@user = User.new user_params
if @user.save
...
end
end
private
def user_params
params.require(:user).permit(:password, :phone, :sms_token, profile_attributes: [:username])
end
end
view中,users/new.html.erb:
<% form_for @user do |f| %>
<%= f.text_field :name %>
<% f.fields_for :profile do |profile_form| %> #注意这里
<%= profile_form.text_field :username %>
<% end %>
<% end %>
这是一对一的情况,假设是一对多呢:
在has_many中:User#@user.profiles.build,视图里面的profile,以及user_params里面的
profile_attributes要改成profiles_attributes
在has_one中:User#build_profile