我无法解决这个错误。
NoMethodError in ValuationsController#like
undefined method `valuation_likes` for #<User:0x007fb3b21b9fc8>
#LINE IN VALUATIONS_CONTROLLER: @valuation_like = current_user.valuation_likes.build(valuation: @valuation)
代码的目的是让用户喜欢其他用户的价值(又名:valuations
)。
valuations_controller
def like
@valuation = Valuation.find(params[:id])
@valuation_like = current_user.valuation_likes.build(valuation: @valuation)
if @valuation_like.save
@valuation.increment!(:likes)
flash[:success] = 'Thanks for liking!'
else
flash[:error] = 'Two many likes'
end
redirect_to(:back)
end
valuation_like.rb
class ValuationLike < ActiveRecord::Base
belongs_to :valuation
belongs_to :user
validates :user, uniqueness: { scope: :valuation }
belongs_to :liker, class_name: 'User', foreign_key: :user_id
end
valuation.rb
has_many :valuation_likes
has_many :likers, through: :valuation_likes, class_name: 'User', source: :liker
has_many :comment_likes
估值/显示
<% @valuation.likers.each do |user| %>
<%= user.name %>
<% end %>
<%= link_to like_valuation_path(:id => @valuation.id), class: "btn", method: :post do %>
<span class='glyphicon glyphicon-thumbs-up'></span> Like
<% end %>
模式
create_table "valuation_likes", force: true do |t|
t.integer "user_id"
t.integer "name"
t.integer "likes"
t.integer "valuation_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "valuations", force: true do |t|
t.boolean "conceal", default: false
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "likes"
t.text "name"
end
add_index "valuations", ["user_id", "created_at"], name: "index_valuations_on_user_id_and_created_at"
add_index "valuations", ["user_id"], name: "index_valuations_on_user_id"
谢谢!如果您需要更多代码,说明或视觉效果,请与我们联系:)
答案 0 :(得分:1)
我认为在User
模型中,您没有行has_many :valuation_likes
。添加它,它将起作用
答案 1 :(得分:1)
您可以考虑查看polymorphic associations,并制作一个可爱的&#39;可重用性等级。
答案 2 :(得分:1)
正如Arup所说,你的用户模型中没有“has_many”关系。
或者,你可以......
@valuation_like = @valuation.valuation_likes.build(user: current_user)