第二个远程has_many通过关联的select选项helper方法的语法

时间:2014-05-18 11:15:29

标签: ruby-on-rails forms has-many-through form-helpers

如何正确填写以下语法以创建下拉选择标记,其中每个选项都是另一个表的数据?

<%= form_for(@celebrity, :html => { :multipart => true }) do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.label :image %>
  <%= f.file_field :image %>
  <%= f.label :character %>
  <%= f.collection_select(:character, :celebrity_id, @characters, :id, :name)  %>   #this line is the question
  <%= f.submit 'Save' %>
<% end %>

我在这里遵循API文档,但它似乎不起作用。

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select

class Celebrity < ActiveRecord::Base

    has_many :characters, through: :char_celeb_joins
    has_many :char_celeb_joins

    has_many :universes, through: :characters

end


class Character < ActiveRecord::Base

  has_many :universes, through: :univ_char_joins
  has_many :univ_char_joins

  has_many :celebrities, through: :char_celeb_joins
  has_many :char_celeb_joins

end


class Universe < ActiveRecord::Base

    has_many :characters, through: :char_univ_joins
    has_many :char_univ_joins

    has_many :celebrities, through: :characters
end

但是我得到了 undefined method 'merge' for :name:Symbol 在浏览器中,当我转到显示此代码的视图时。 NoMethodError in Celebrities#edit

3 个答案:

答案 0 :(得分:1)

错误是由于这一行

<%= f.collection_select(:character, :celebrity_id, @characters, :id, :name)  %>

form_for一起使用时,您必须像这样设置

<%= f.collection_select(:celebrity_id, @characters, :id, :name)  %>

而且您的form_for object@celebrity,并且您将:character作为collection_select的对象。:celebrity中应为collection_select在没有collection_select的情况下使用form_for时,您会担心这一点。在您的情况下,它会是

<%= collection_select(:celebrity, :celebrity_id, @characters, :id, :name)  %>

答案 1 :(得分:0)

您可以使用帮助:

在任何帮助程序中编写此代码:

def character_for_select
   Character.all.collect { |m| [m.id, m.name] }
end

更新表单

<%= form_for(@celebrity, :html => { :multipart => true }) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :image %>
<%= f.file_field :image %>
<%= f.label :character %>
<%= f.select(:character, character_for_select, :prompt => 'Select character') %>
<%= f.submit 'Save' %>
<% end %>

你会得到答案:)

答案 2 :(得分:-1)

您是否尝试过使用options_for_select。在您的情况下,您的代码应该是这样的:

应用/助手...

def options_for_characters( selected=nil )
  options = Character.all.map { |c| [d.id, c.name] }
  options_for_select( options, selected )
end

应用/视图...

   ...
   <%= f.select(:character, options_for_characters, :prompt => 'Select character') %>
   ...