Create a like button with Stimulus Reflex

365 Views Asked by At

business class

class Business < ApplicationRecord
    .........
    belongs_to :user 
    has_many :likes

like class

class Like < ApplicationRecord
  belongs_to :user  
  belongs_to :business
  .....

user class

class User < ApplicationRecord
  has_many :likes
  has_many :businesses
  ....

business/show.html.erb

<%= button_tag "Like", data: {reflex: "click->Likes#like", id: @business.id} %>


class LikesReflex < ApplicationReflex  
 def like    
 business = Business.find(element.dataset[:id])    
 business.likes.find_or_create_by(user: current_user)  
 ......

i need help to set the likeReflex controller . i want login user to like business and add them to thier user.likes

1

There are 1 best solutions below

1
On

This is how I would implement a like button in StimulusReflex.

In the view template:

<%= button_tag "Like", data: {reflex: "click->Posts#like, id: @post.id} %>

In your reflex class:

class PostsReflex < ApplicationReflex
  def like
    post = Post.find(element.dataset[:id])
    post.likes.find_or_create_by(user: current_user)
  end
end

A common pattern, which is more secure is to use signed global ids, then you can have create something that works more like a concern:

<%= button_tag "Like", data: {reflex: "click->Likes#create", sgid: @post.to_sgid_param } 

Then you have a Reflex class like:

class LikesReflex < ApplicationReflex
  def create
    likeable = GlobalID::Locator.locate_signed(element.dataset[:sgid])
    likeable.likes.find_or_create_by(user: current_user)
  end
end