简体   繁体   中英

how to count messages for mailboxer gem

hi am using merit to grant badges to users that send messages through mailbox. i have setup mailboxer and its working fine in which users can have a conversation and send messages to each other. from that i added merit to grant badges to users that send message like this

grant_on 'messages#create',  badge: 'Engraved Glass', to: :user do    |message|
    message.user.messages.count >= 50
end

but when ever i create new message i get this error

undefined method `user' for true:TrueClass

but when its sending message on a old conversation it doesnt throw this error

This is a little tricky. When you're working with a more straighforward setup, for example a Comment model, with a comments_controller and a @comment object, then what you're proposing would be fine. But because this is a messages_controller, who knows what your mailboxer object is called and :user isn't an attribute on the object anyway.. it all goes amuck.

But we can fix it. There's a couple of rules here if the model and controller are not the same.

  1. Make sure you define an object. Mailboxer expects the messages_controller to define a @message object - So in your create action of messages make sure that you set it @message = current_user.send_message(to_user, params[:message][:message_body],params[:message][:subject]) - must be an instance variable using the @ sign

  2. Make sure you set the proper attribute for a user. In your case, with Mailboxer, it's going to be :receiver

  3. Since :receiver doesn't align directly to a model, give it the model name model_name "User"

So now your grant will look more like

grant_on 'messages#create', badge: 'Engraved Glass', to: :receiver, model_name: "User" do |message|
 message.receiver.messages.count >= 50
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM