12

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

回答

14

使用f.simple_fields_for而不是simple_fields_for

<%= f.simple_fields_for :profile do |p| %> 
    <%= p.input :name %> 
<% end %> 
+0

哎唷! Thx很多@Bigxiang :) –

+0

這從字面上節省了我的時間。 – Kyle

1

在我來說,我有對象的「書」屬於「遊」,「遊」的has_many「書」。

在該方法中的「BookController的」「新」,我覺得旅遊和初始化書對象:

@tour = Tour.find(params[:tour_id])

@book = Book.new 

這是部分形式創建了一本書:_form.html .erb

<%= simple_form_for [@tour, @book] do |f| %> 
    <%= f.input :name, label: "Name"%> 
    <%= f.input :NoReservations, label: "Number of Reservations" %> 
    <%= f.input :email, label: "Email" %> 
    <h3>Num of available places</h3> 
    <%= f.button :submit %> 
<% end %>