collection_select输入的NoMethodError

时间:2015-03-28 22:59:44

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

我一直在尝试不同的方法来解决这个问题,这让我疯狂......

我有一个输入字段:

<%= collection_select(:stakeholder, :user_id, User.all, :id, :first_name) %>

每个利益相关者都有一个user_id属性,它是一个整数。

当我尝试渲染表单时,我得到了NoMethodError:

undefined method `id' for 2:Fixnum

有什么想法吗?

修改:添加完整表单视图

 <%= simple_form_for([@project, @stakeholder]) do |f| %>
 <%= f.error_notification %>

 <div class="form-inputs">
  <%= f.input :first_name %>
  <%= f.input :last_name %>
  <%= f.input :email %>
  <%= f.input :address %>
  <%= f.input :city %>
  <%= f.input :sentiment,  %>
  <%= f.label :tags, "Tags (separated by commas)" %>
  <%= collection_select(:stakeholder, :user_id, User.all, :id, :first_name) %>
  <%= f.button :submit %>
</div>

user.rb

class User < ActiveRecord::Base

belongs_to :account
has_many :stakeholders

def set_default_role
 self.role ||= :user
end

# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :invitable, :database_authenticatable, :registerable, :confirmable,
     :recoverable, :rememberable, :trackable, :validatable
end

stakeholder.rb

class Stakeholder < ActiveRecord::Base
 belongs_to :project
has_many :notes
belongs_to :user
acts_as_taggable

def full_name
  full_name = "#{first_name.capitalize} #{last_name.capitalize}"
end

end

1 个答案:

答案 0 :(得分:0)

看看这个documentation

collection_select(object, method, collection, value_method,
text_method, options = {}, html_options = {}) public

Returns <select> and <option> tags for the collection of existing
return values of method for object's class. The value returned from
calling method on the instance object will be selected.

您的collection_select标记中似乎有一个额外的参数,导致Rails在实际上是一个数字(2)时调用:id作为方法。

user_id是某个Stakeholder对象中的一个字段,对吗?因此,除非我误解你如何建立你的关系,否则利益相关者是不相关的(从某种意义上说,你想要的只是你表单中的用户ID)。

这一行可以满足您的需求。

<%= f.collection_select(:user_id, @users, :id, :first_name)