Leo Bogod
Leo Bogod

Reputation: 419

Rails Merit undefined local variable or method `user' for #<Merit::BadgeRules:0x0000000415b5e0>

im trying to build a reputation system with rails using the merti gem , im trying to grant a badge when the user creates more than 8 comments however im getting an error undfined method user everytime i create a comment. I m using devise , but i can create a badge manually. can someone please help? thanks !!

badge rules

# Be sure to restart your server when you modify this file.
#
# +grant_on+ accepts:
# * Nothing (always grants)
# * A block which evaluates to boolean (recieves the object as parameter)
# * A block with a hash composed of methods to run on the target object with
#   expected values (+votes: 5+ for instance).
#
# +grant_on+ can have a +:to+ method name, which called over the target object


module Merit
  class BadgeRules
    include Merit::BadgeRulesMethods

    def initialize

      grant_on 'comments#create',  badge: 'Jr.Critic', temporary: true, to: :user do |comment|
  comment.user.comments.count >= 1 &&  comment.user.comments.count < 2
end
grant_on 'comments#create',  badge: 'Sr.Critic', to: :user do |comment|
  comment.user.comments.count >= 3
end
grant_on 'notes#create',  badge: 'First story ', to: :user do |note|
note.user.notes.count = 1
end

grant_on 'comments#create',  badge: 'Story Teller', to: :user do |comment|
comment.user.comments.count >= 8
end

merit.rb

# Use this hook to configure merit parameters
Merit.setup do |config|


  Merit::Badge.create!(
  id: 1,
  name: "Jr.Critic",
  description: "Over 5 comments"
)
Merit::Badge.create!(
  id: 2,
  name: "Sr.Critic",
  description: "Over 50 comments"
)

Merit::Badge.create!(
id: 3,
name: "Story Teller",
description: "Over 5 notes!"
)
Merit::Badge.create!(
id: 4,
name: "First story ",
description: "created first story"
)


Merit::Badge.create!(
id: 5,
name: "commenter ",
description: "created more than 5 comments!"
)

and user model

class User < ApplicationRecord
  has_merit

 end

Upvotes: 0

Views: 93

Answers (2)

Rockwell Rice
Rockwell Rice

Reputation: 3002

It looks like you did not set up your association for user and comments

User.rb should also have, along with the has_merit, has_many :comment

class User < ApplicationRecord
  has_merit
  has_many :comments
end

Comment.rb should have the belongs_to :user

class Comment < ApplicationRecord
  belongs_to :user
end

Also, do not forget to set the associations for notes if you did not as well.

Upvotes: 1

Leon Bogod
Leon Bogod

Reputation: 428

you need run a migration for merit comments. then restart your server and change this line

grant_on 'notes#create',  badge: 'First story ', to: :user do |note|
note.user.notes.count = 1
end

to

grant_on 'notes#create',  badge: 'First story ', to: :user do |note|
    note.user.notes.count = >1
    end

hope it works for you

Upvotes: 0

Related Questions