0

商务课程

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

喜欢上课

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

用户类

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

业务/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)  
 ......

我需要帮助来设置 likeReflex 控制器。我希望登录用户喜欢业务并将它们添加到他们的 user.likes

4

1 回答 1

1

这就是我在 StimulusReflex 中实现类似按钮的方式。

在视图模板中:

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

在你的反射课上:

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

一个更安全的常见模式使用已签名的全局 ids,然后您可以创建一些更像关注点的东西:

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

然后你有一个反射类,如:

class LikesReflex < ApplicationReflex
  def create
    likeable = GlobalID::Locator.locate_signed(element.dataset[:sgid])
    likeable.likes.find_or_create_by(user: current_user)
  end
end  
于 2021-03-19T07:40:02.847 回答