【问题标题】:Socialization likes社会化喜欢
【发布时间】:2015-08-29 16:36:21
【问题描述】:

我开始使用Socialization gem。 因此,使用设计创建了用户模型:

class User < ActiveRecord::Base
    has_many :posts
    devise :database_authenticatable, 
    :registerable,
    :recoverable, 
    :rememberable, 
    :trackable, 
    :validatable

    acts_as_follower
    acts_as_followable
    acts_as_liker
end

然后我用脚手架创建了 Post:

class Post < ActiveRecord::Base
   belongs_to :user
   acts_as_likeable
end

我想允许用户喜欢帖子。但是我不知道如何用like按钮创建视图,也不知道如何编写like方法。请给我一个小例子。我是 Rails 新手

我在veiw/posts/show.html.erb 中创建链接。

<%= link_to "Like", like_post_path(@post), 
:method => :post, :class => 'btn btn-primary btn-xs' %>

以及app_contoller中的方法:

def like        
    @post = Post.find(params[:id])
    current_user.like!(@post)       
end

如何为此编写路线?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 social-media-like


    【解决方案1】:

    您已经可以先在控制台中进行测试,看看它是如何工作的:rails c

    user = User.first
    post = Post.first
    user.like!(post)
    user.likes?(post)
    

    因此您可以在 Posts 控制器中创建一个操作:likes

    def likes
      @user = current_user # before_action :authenticate_user, only: [:likes]
      @post = Post.find(params[:id])
      @user.like!(@post)
      redirect_to :back, notice: "Liked this post successfully!"
    end
    

    并为该操作创建路线:

    get 'post/:id/likes', to: 'posts#likes', as: :likes
    

    在你看来:

    <%= link_to 'like', likes_path(@post) %>
    

    【讨论】:

      猜你喜欢
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多