我想在另一个(嵌套)的同时创建一个资源。我使用Rails4和simple_form 3.0.0rc。这是我的代码。
型号:我应该如何使用rails和simple_form嵌套资源?
class User < ActiveRecord::Base
has_one :profile
accepts_nested_attributes_for :profile
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
user.save
redirect_to root_url
# @par =params
end
private
def user_params
params.require(:user).permit(:email, profile_attributes: [:name])
end
end
视图(形式为新用户)
<%= simple_form_for @user do |f| %>
<%= f.input :email %>
<%= simple_fields_for :profile do |p| %>
<%= p.input :name %>
<% end %>
<%= f.submit %>
<% end %>
当我提交表单,创建行动recive此PARAMS:
{"utf8"=>"✓", "authenticity_token"=>"dJAcMcdZnrtTXVIeS2cNBwM+S6dZh7EQEALZx09l8fg=", "user"=>{"email"=>"[email protected]"}, "profile"=>{"name"=>"Vasily"}, "commit"=>"Create User", "action"=>"create", "controller"=>"users"}
,并呼吁“user_params”后留下的唯一的事情就是
{"email"=>"[email protected]"}
而且,正如你所看到的,没有什么关于“个人资料”,所以没有配置文件将被创建。
我在做什么错?
P.S.对不起我的英语不好。
哎唷! Thx很多@Bigxiang :) –
这从字面上节省了我的时间。 – Kyle