简体   繁体   中英

Allowing user to favorite a post

I'm working on allowing a user to favorite a post.

I've created a model called favorite.

belongs_to :user
belongs_to :post

it stores the user_id and post_id.

I've also created a FavoritesController

class FavoritesController < ApplicationController

  def create
    @post = Post.find(params[:post_id])
    current_user.favorite(@post)
  end

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

end

the form I have on my Posts#index is:

<%= form_for current_user.favorites.build do |favorite| %>
  <%= hidden_field_tag :post_id, f.id %>
  <%= favorite.button do %>
    <i class="fa fa-star-o"></i>
  <% end %>
<% end %>

my user model looks like this:

# Favorites a post.
def favorite(post)
  favorite.create(post_id: post)
end

# Unfavorites a post.
def unfavorite(post)
  favorite.find_by(post_id: post).destroy
end

when I try to click on favorite I get:

wrong number of arguments (0 for 1)

Parameters:

{"utf8"=>"✓",
  "authenticity_token"=>"HjiANQUqTQVEqy0yzfLFMlnC8RsTiY5kVlvIUnD5OSIaSYSi4ELSuC95vRMIBA/6W+KvzCWMMXQ==",
"post_id"=>"7",

What am I doing wrong here? Also is there a better way to do this?

如果您只是想让“投票/收藏夹”系统正常工作,我建议您使用https://github.com/ryanto/acts_as_votable之类的gem。

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