[英]Rails Favorite_posts: “Couldn't find Post with an ID”
BLUF: Trying to make a Favorite_posts feature; BLUF:尝试创建Favorite_posts功能; I can verify that it works by manually setting the ActiveRecord in the Rails console, 我可以通过在Rails控制台中手动设置ActiveRecord来验证其是否有效,
But the links I made give the error: "Couldn't find Post without an ID" 但是我创建的链接给出了错误: “找不到没有ID的帖子”
The Form: 表格:
<% 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 %>
The Controller: 控制器:
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
The Models: 型号:
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'
The Routes: 路线:
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]
您是否尝试过将@ post.id而不是@post传递到您的网址,
favorite_posts_path(id: @post.id)
修正:我已经从_post部分项中重构出了这种形式,当我放回去时它工作得很好。我认为后端只是为那个控制器设置的,我不在乎重构它适当地
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.