Accepts_nested_attributes_for连接has_many通过关系的表

时间:2013-12-04 04:07:34

标签: ruby-on-rails ruby ruby-on-rails-4 simple-form has-many-through

我有一个has_many through关系,我试图在创建过程中将属性保存到连接表。我已经阅读了我在网上找到的所有内容,但似乎无法获得任何实际保存的内容。 Rails 4 app使用simple_form。

模型设置

class Request < ActiveRecord::Base
  has_many :line_items, through: :requestables
  has_many :requestables
end

class LineItem < ActiveRecord::Base
  has_many :requests, through: :requestables, dependent: :destroy 
  has_many :requestables

  accepts_nested_attributes_for :requestables
end

 class Requestable < ActiveRecord::Base
   belongs_to :line_item
   belongs_to :request
   validates :line_item_id, presence: true
   validates :request_id, presence: true
 end

表单的相关部分

<%= simple_form_for ([@request, @line_item]), remote: true do |f| %>
<%= f.error_notification %>
    <div class="form-inputs">
    <%= f.input :name, :required => true, :autofocus => true  %>
    <%= f.simple_fields_for :requestables do |r| %>
      <%= r.input :quantity, :required => true %>
      <% end %>
 *rest of form*

controller(我在Index页面上创建LineItems)。我添加了@ line_item.requestables.build,因此我可以将其包含在表单中。

class LineItemsController < ApplicationController

def index
  @request = Request.find(params[:request_id])
  @line_item = @request.line_items.build
  @line_item.requestables.build
end

def create
  @request = Request.find(params[:request_id])
  @line_item = @request.line_items.create(line_item_params)
  if @line_item.save
    respond_to do |format|
     format.html { redirect_to :action => :index }
     format.js { flash.now[:success] = "Boom" }
    end
  else
    redirect :action => index
  end

private
  def line_item_params
    params.require(:line_item).permit(:name, :requestables_attributes => [:quantity])
  end 
end

我想创建一个新的LineItem,同时将数量保存到连接表/请求中。我似乎有一切正确 - 当我没有在表单中包含数量时,它正确保存LineItem并自动创建连接表。但是当我使用about代码时,我得到以下内容:

Processing by LineItemsController#create as JS
Parameters: {"utf8"=>"√", "line_item"=>{"name"=>"Pillow", "requestables_attributes"=>{"0"=>{"quantity"=>"11"}}}, "commit"=>"Add to List", "request_id"=>"5"}
User Load (1.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Request Load (1.0ms)  SELECT "requests".* FROM "requests" WHERE "requests"."id" = $1 LIMIT 1  [["id", "5"]]
CACHE (0.0ms)  SELECT "requests".* FROM "requests" WHERE "requests"."id" = $1 LIMIT 1  [["id", "5"]]
(0.0ms)  BEGIN
(0.0ms)  COMMIT
(0.0ms)  BEGIN
(0.0ms)  ROLLBACK
Redirected to http://localhost:3000/requests/5/line_items
Completed 302 Found in 19ms (ActiveRecord: 2.0ms)

它无法保存任何内容,只是重定向。

我可以通过保存后立即用数量更新请求数来实现我想要的结果,但这似乎不是Rails方式,我无法获取编辑表单的数量。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:-3)

当您使用Rails4时,请确保您有

# attr_accessible
gem 'protected_attributes'

gem在Gemfile中并使用attr_accessible

# Setup accessible (or protected) attributes for your model----------
attr_accessible :name, :requestables_attributes

Rails 4现在使用strong parameters

为了将accepts_nested_attribute_for与强参数一起使用,您需要指定哪些嵌套属性应列入白名单。