12

Próbuję utworzyć jeden zasób z innym (zagnieżdżonym) w tym samym czasie. Używam Rails4 i simple_form 3.0.0rc. Oto mój kod.
Modele:Jak używać szyn i prostych_formatów dla zasobów zagnieżdżonych?

class User < ActiveRecord::Base 
    has_one :profile 
    accepts_nested_attributes_for :profile 
end 

class Profile < ActiveRecord::Base 
    belongs_to :user 
end 

Kontroler:

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 

View (formularz dla nowego użytkownika)

<%= simple_form_for @user do |f| %> 
    <%= f.input :email %> 
    <%= simple_fields_for :profile do |p| %> 
    <%= p.input :name %> 
    <% end %> 
    <%= f.submit %> 
<% end %> 

Kiedy przesłać formularz, należy utworzyć działanie recive to params:

{"utf8"=>"✓", "authenticity_token"=>"dJAcMcdZnrtTXVIeS2cNBwM+S6dZh7EQEALZx09l8fg=", "user"=>{"email"=>"[email protected]"}, "profile"=>{"name"=>"Vasily"}, "commit"=>"Create User", "action"=>"create", "controller"=>"users"} 

A po wywołaniu „user_params” jedyną rzeczą, która pozostaje, to

{"email"=>"[email protected]"} 

I, jak widać, nie ma nic o „profilu”, więc nie zostanie utworzony profil.
Co robię źle?

P.S. przepraszam za mój angielski.

Odpowiedz

14

Zastosowanie f.simple_fields_for zamiast simple_fields_for:

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

Ouch! Thx dużo @Bigxiang :) –

+0

To dosłownie uratowało mi godziny. – Kyle

1

W moim przypadku miałem obiektu "książki", która należy do "tour" i "Tour" has_many "książki".

W „BookController” w metodzie „nowy” znajdę wycieczkę i zainicjować obiektu rezerwacji:

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

@book = Book.new 

Jest to częściowa forma stworzyć książkę: _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 %> 
Powiązane problemy