使用has_many的collection_check_boxes困难:通过连接模型

时间:2015-05-17 16:10:07

标签: ruby-on-rails ruby-on-rails-4

尝试将属性保存到连接模型时出现问题。我收到错误:wrong number of arguments (0 for 1..2)

我以前在其他应用程序中实现了这个问题,所以在我出错的地方会让人感到特别困惑。

我有以下型号:

class Product < ActiveRecord::Base
  has_attached_file :product_image, :styles => { :medium => "250x250>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
  validates_attachment_content_type :product_image, :content_type => /\Aimage\/.*\Z/
  has_many :package_items
  has_many :packages, through: :package_items
end

-

class PackageItem < ActiveRecord::Base
    belongs_to :package 
    belongs_to :product
end

-

class Package < ActiveRecord::Base
  has_attached_file :package_image, :styles => { :medium => "200x200>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
  validates_attachment_content_type :package_image, :content_type => /\Aimage\/.*\Z/
  has_many :package_items
  has_many :products, through: :package_items
end

当我保存包时,它应该将包中包含的所有产品保存在package_items表中。我在表单中使用collection_check_boxes帮助程序,这很正常。

 <%= form_for @package,  :url => packages_path, :html => { :multipart => true } do |f| %>
  <% if @package.errors.any? %>
    <div id="error_explanation" class="center">
      <h2><%= pluralize(@package.errors.count, "error") %> prohibited this package from being saved:</h2>

      <ul>
      <% @package.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  <div class="col-xs-12 field">
    <%= f.label :name, 'Package Name', :class => "text-center form-header" %><br>
    <%= f.text_field :name, :class => "text-center form-text"  %>
  </div>
  <br>
  <br>
  <br>
  <div class="col-xs-12 field">
    <%= f.label :package_image, 'Package Image', :class => "text-center form-header" %><br>
    <%= f.file_field :package_image %>
  </div>
  <br>
  <br>
  <br>
  <div class="col-xs-12 field">
    <%= f.label :price, 'Price Per Day', :class => "text-center form-header" %><br>
    <%= f.number_field :price, :class => "text-center form-text"  %>
  </div>
  <br>
  <br>
  <div class="col-xs-12 field">
  <%= f.label :products %><br>
    <%= f.collection_check_boxes :product_ids, Product.all, :id, :name, {}, { :multiple => true } %>
  </div>
  <br>
  <br>
  <div class="col-xs-12 actions">
    <%= f.submit %>
  </div>
<% end %>

然而,当我提交表单时,我收到wrong number of arguments (0 for 1..2)错误,突出显示我在包控制器中的强params方法:

def package_params
      params.require(:package).permit(:name, :price, :package_image, :product_ids [])
    end

我在日志中看不到任何明显的东西。任何指针都将非常感激。感觉就像我在这个阶段经历了所有的网络和SO而且我无法超越这个。基本上我想要达到的目标与this SO post相同。

1 个答案:

答案 0 :(得分:1)

当然这很简单。丢失的哈希火箭

:product_ids => []

强烈的参数。