当我运行这样的动作
时,我的代码有效def interest
@interest = Interest.new
@interest.user_id = current_user.id
@interest.idea_id = @idea.id
@interest.save
@ideas = Idea.take(10)
flash[:notice] = "A message has been sent to the poster."
render "ideas/forum"
end
但是,当我在我的兴趣行动中使用这一行时,为什么我会得到一个未定义的'兴趣'方法?
@interest = current_user.ideas.interest.create(params[:interest])
这是我的想法模型
class Idea < ActiveRecord::Base
belongs_to :user
:title
:category
:content
:user_id
:createdDate
:updatedDate
这是我的用户模型(设计)
class User < ActiveRecord::Base
has_many :ideas
has_many :interests
end
以下是button_to
代码
<%= button_to "I'm Interested", ideas_interest_path(:id => idea.id, :idea_id => idea.id, :user_id => idea.user_id) ,class: 'btn btn-primary' %>
我的路线,
resources :ideas do
resources :interests
end
兴趣模型 类兴趣&lt;的ActiveRecord :: Base的 belongs_to:用户 belongs_to:idea
has_many:用户
:idea_id :USER_ID
端
NoMethodError - undefined method `interest' for #<Idea::ActiveRecord_Associations_CollectionProxy:0x007f9e5189bab0>:
activerecord(4.2.0)
答案 0 :(得分:1)
我认为你搞砸了这个联想,我会这样做:
class User < ActiveRecord::Base
has_many :interests
has_many :ideas, through: :interests
end
class Interest < ActiveRecord::Base
belongs_to :user
belongs_to :idea
# user_id, idea_id
end
class Idea < ActiveRecord::Base
has_many :interests
has_many :users, through: :interests
end
然后我猜其余的都会奏效。