【问题标题】:Wrong number of Arguments error in collection_selectcollection_select 中的参数错误数量错误
【发布时间】:2015-06-21 15:06:46
【问题描述】:

我有一个表格;

<%= form_for @boats do |f| %>

<%= f.collection_select(:brand, :brand_id,  @brands,  :id, :name, {:prompt   => "Select a Brand"}, {:id => 'brands_select'}) %>

<%= f.collection_select(:year, :year_id, @years, :id, :name, {:prompt   => "Select a Year"}, {:id => 'years_select'}) %>

<%= f.collection_select(:model, :model_id, @models, :id, :name, {:prompt   => "Select a Model"}, {:id => 'models_select'}) %>
<%= f.submit "Create my account" %>

    <% end %> 

并且有控制器#index;

def index
    @boats = Boat.new
    @brands  = Brand.all
    @years = Year.all
    @models   = Model.all
  end

但这里的问题是,当我运行代码时,它给出了一个错误;

所以我不知道该怎么做。基本上,数据来自数据库,我想将它们保存到列名为 Brand、Year 和 Model 的 Boat 数据库中。

【问题讨论】:

  • 您给出的最后 2 个参数是 2 个不同的哈希,而不是只有一个。请改用{:prompt =&gt; "Select a Brand", :id =&gt; 'brands_select'}
  • 谢谢@MrYoshiji。但现在又出现了一个错误:NoMethodError in HomeController#index, undefined method merge' for :name:Symbol

标签: ruby-on-rails collection-select


【解决方案1】:

参数的正确顺序是:

method, collection, value_method, text_method, options = {}, html_options = {}

即:

<%= f.collection_select :brand_id, @brands, :id, :name, {prompt: 'Select a Brand'}, {id: 'brand_select'} %>

【讨论】:

  • 但这一次它保存的是 id,而不是名称; SELECT "boats".* FROM "boats" ORDER BY "boats"."id" ASC LIMIT 1 => #
  • 看,您不需要将这些名称存储在船的记录中。将它们保存在适当模型(品牌、模型等)的表中,您可以通过主键 (id) 引用这些表。这就是关系数据库和 ActiveRecord 的设计目的。您可以使用以下语法来获取船品牌名称:boat.brand.name.
猜你喜欢
  • 2014-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多