简体   繁体   English

如何将嵌套属性与simple_form,Rails 4和has_many一起使用?

[英]How should I use nested attributes with simple_form, Rails 4, and has_many?

I'm trying to use simple_form to create an object and one of its has_many associations with Rails 4. 我正在尝试使用simple_form创建一个对象及其与Rails 4的has_many关联之一。

Here's what I have so far: 这是我到目前为止的内容:

class User < ActiveRecord::Base
  has_many :applications
  accepts_nested_attributes_for :applications
end

class Application < ActiveRecord::Base
  belongs_to :user

  def self.allowed_params
      [:over_18]
  end
end

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new user_params
    @user.save
    # there is more in here, but I don't think it's relevant
  end

  private
  def user_params
    params.require(:user).permit(:name, :email, application: Application.allowed_params)
  end
end

And finally the form itself 最后是表格本身

<%= simple_form_for @user do |f| %>
  <%= f.input :name %>
  <%= f.simple_fields_for :application do |a| %>
    <%= a.input :over_18, label: 'Are you over 18?', as: :radio_buttons %>
  <% end %>
  <%= f.button :submit %>
<% end %>

Whenever I try to create a new user with this setup I get an error: ActiveRecord::UnknownAttributeError: unknown attribute 'application' for User. 每当我尝试使用此设置创建新用户时,都会出现错误: ActiveRecord::UnknownAttributeError: unknown attribute 'application' for User.

Question: What should I change so I can create new users with a nested application? 问题:我应该更改什么才能使用嵌套应用程序创建新用户?

I've tried changing f.simple_fields_for :application to f.simple_fields_for :applications but then simple_fields didn't render the form elements. 我尝试将f.simple_fields_for :application更改为f.simple_fields_for :applications但是simple_fields没有呈现表单元素。

A couple of changes should fix your issue: 进行一些更改可以解决您的问题:

  1. Ensure @user object has an application instance built before the form is rendered. 确保@user对象在呈现表单之前已构建了一个application实例。
  2. Ensure you use form_builder.simple_fileds_for :applications , ie plural applications as your association is has_many . 确保使用form_builder.simple_fileds_for :applications ,即复数applications因为您的关联为has_many

Changes to your Users Controller: 对用户控制器的更改:

class UsersController < ApplicationController
  def new
    @user = User.new
    @user.applications.build
  end
end

Changes to your view: 对视图的更改:

<%= f.simple_fields_for :applications do |a| %>
  <%= a.input :over_18, label: 'Are you over 18?', as: :radio_buttons %>
<% end %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM