【问题标题】:How should I use rails and simple_form for nested resources?我应该如何将 rails 和 simple_form 用于嵌套资源?
【发布时间】:2013-08-26 04:46:29
【问题描述】:

我正在尝试同时创建一个资源和另一个嵌套资源。我正在使用 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 没有任何内容,因此不会创建个人资料。

我做错了什么?

【问题讨论】:

    标签: ruby-on-rails simple-form nested-attributes fields-for strong-parameters


    【解决方案1】:

    使用f.simple_fields_for 代替simple_fields_for

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

    【讨论】:

    • 哎哟!非常感谢@Bigxiang:)
    • 这确实为我节省了几个小时。
    • 大声笑,我真的很难过。谢谢。如此明显,不知道为什么认为 simple_form xD 会有所不同
    【解决方案2】:

    在我的例子中,我有属于“tour”和“tour”的对象“book”有_many“books”。

    在“new”方法中的“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 %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-02
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多