如何为嵌套资源使用rails和simple_form? [英] How should I use rails and simple_form for nested resources?

查看:86
本文介绍了如何为嵌套资源使用rails和simple_form?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试同时创建一个资源和另一个嵌套资源.我正在使用Rails4和simple_form 3.0.0rc.这是我的代码.

I'm trying to create one resource with another nested resource at the same time. I'm using Rails4 and simple_form 3.0.0rc. Here is my code.

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:

When I submit the form, the create action receives this params:

{"utf8"=>"✓",
"authenticity_token"=>"dJAcMcdZnrtTXVIeS2cNBwM+S6dZh7EQEALZx09l8fg=", 
"user"=>{"email"=>"vasily.sib@gmail.com"},
"profile"=>{"name"=>"Vasily"},
"commit"=>"Create User",
"action"=>"create",
"controller"=>"users"}

在调用user_params之后,剩下的唯一内容是

And after calling user_params the only thing that left is

{"email"=>"vasily.sib@gmail.com"}

而且,如您所见,profile没有任何内容,因此不会创建任何配置文件.

And, as you can see, there is nothing about profile, so no profile will be created.

我在做什么错了?

推荐答案

使用f.simple_fields_for代替simple_fields_for:

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

这篇关于如何为嵌套资源使用rails和simple_form?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆