Search code examples
ruby-on-railsrubynomethoderror

NoMethodError in Controller#like


I can't for the life of me figure out this error.

enter image description here

NoMethodError in ValuationsController#like 
undefined method `valuation_likes` for #<User:0x007fb3b21b9fc8>
#LINE IN VALUATIONS_CONTROLLER: @valuation_like = current_user.valuation_likes.build(valuation: @valuation)

The purpose of the code is so that user's can like other user's values (aka :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

valuations/show

<% @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 %>

schema

  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"

Thank you! Please let me know if you need anymore code, explanation, or visuals :)


Solution

  • I think in User model, you don't have the line has_many :valuation_likes. Add it, and it will work