[英]How should I use rails and simple_form for nested resources?
我正在嘗試同時使用另一個嵌套資源創建一個資源。 我正在使用Rails4和simple_form 3.0.0rc。 這是我的代碼。
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 %>
當我提交表單時, create
操作會收到此params
:
{"utf8"=>"✓",
"authenticity_token"=>"dJAcMcdZnrtTXVIeS2cNBwM+S6dZh7EQEALZx09l8fg=",
"user"=>{"email"=>"vasily.sib@gmail.com"},
"profile"=>{"name"=>"Vasily"},
"commit"=>"Create User",
"action"=>"create",
"controller"=>"users"}
在調用user_params
,唯一剩下的就是
{"email"=>"vasily.sib@gmail.com"}
而且,正如您所看到的, profile
沒有任何內容,因此不會創建任何配置文件。
我究竟做錯了什么?
使用f.simple_fields_for
而不是simple_fields_for
:
<%= f.simple_fields_for :profile do |p| %>
<%= p.input :name %>
<% end %>
在我的情況下,我有對象“書”屬於“旅游”和“旅游”has_many“書籍”。
在方法“new”的“BookController”中,我找到了tour並初始化了book對象:
@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 %>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.