我想在另一個(嵌套)的同時創建一個資源。我使用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