BLUF:尝试制作Favorite_posts功能;我可以通过在Rails控制台中手动设置ActiveRecord来验证它是否有效,
但我所做的链接会出错:"无法找到没有ID的帖子"
表格:
<% if logged_in? %>
<% unless current_user.favorite_posts.exists?(id: @post.id) %>
<%= link_to favorite_posts_path(post_id: @post), method: :post do %>
<span class="glyphicon glyphicon-star-empty"></span>
<% end %>
<% else %>
<%= link_to favorite_post_path(@post), method: :delete do %>
<span class="glyphicon glyphicon-star"></span>
<% end %>
<% end %>
<% end %>
控制器:
class FavoritePostsController < ApplicationController
before_action :logged_in_user, :set_post
def create
Favorite.create(favorited: @post, user: current_user)
respond_to do |format|
format.html
format.js
end
end
def destroy
Favorite.where(favorited_id: @post.id, user_id: current_user.id).first.destroy
respond_to do |format|
format.html { redirect_to @user }
format.js
end
end
private
def set_post
@post = Post.find(params[:post_id] || params[:id])
end
end
模特:
class Post < ApplicationRecord
belongs_to :user
class Favorite < ApplicationRecord
belongs_to :favorited, polymorphic: true
belongs_to :user
end
class User < ApplicationRecord
extend FriendlyId
friendly_id :name
has_many :posts, dependent: :destroy
has_many :favorites
has_many :favorite_posts, through: :favorites, source: :favorited, source_type: 'Post'
路线:
resources :users do
collection do
match 'search' => 'users#index_gyms', via: [:get, :post], as: :search
end
member do
get :following, :followers
get :favorite_posts
end
end
resources :favorite_posts, only: [:create, :destroy]
答案 0 :(得分:0)
您是否尝试将@ post.id而不是@post传递到您的网址
favorite_posts_path(id: @post.id)
答案 1 :(得分:0)
固定:我从_post部分项目中重构了这个表单,当我把它重新插入时它运行正常。我认为后端只是为那个控制器设置的,我不在乎足以正确地重构它