1

我开始使用社会化宝石。因此,使用设计创建了用户模型:

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

如何为此编写路线?

4

1 回答 1

1

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

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

所以你可以创建一个动作:likes在你的 Posts 控制器中。

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) %>
于 2015-06-13T22:04:22.563 回答