You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails API项目需求:获取特定ID数据而非全部数据

How to Fetch a Specific Post ID in Your Rails API

Let's adjust your current setup to retrieve data for a single specific post ID instead of all posts. Here's how to modify each part step by step:

1. Update Your Route

First, change your existing route to accept a dynamic :id parameter so we can pass the specific post ID we want:

# config/routes.rb
get 'club_post/:id' => 'clubs#club_post'

This route will match URLs like /club_post/123 where 123 is the ID of the post you want to fetch.

2. Create a New Controller Action

Add a new action in your ClubsController to handle fetching the single post, while keeping the check to exclude posts hidden by the current user:

# app/controllers/clubs_controller.rb
def club_post
  # Fetch the post by ID (returns nil if not found, avoiding exceptions)
  @post = Post.find_by(id: params[:id])

  if @post.nil?
    # Handle case where post doesn't exist
    render json: { error: "Post not found" }, status: :not_found
    return
  end

  # Check if the current user has hidden this post (optimized database query)
  if current_user.hide_posts.exists?(post_id: @post.id)
    render json: { error: "Post is hidden by user" }, status: :forbidden
    return
  end
end
  • find_by(id: params[:id]) is safer than find(params[:id]) because it avoids raising an exception if the post doesn't exist.
  • We use exists? instead of pluck for the hidden post check to keep the logic in the database, which is more efficient for large datasets.

3. Adjust Your JBuilder Template

Create a new JBuilder template named club_post.json.jbuilder (matching your action name) to render the single post's data:

# app/views/clubs/club_post.json.jbuilder
if @post
  json.extract! @post, :id, :title, :content, :created_at, :updated_at
  # Add any other post attributes you want to include here
else
  json.error "Post not found"
end

This will render the full details of the specific post if it exists and isn't hidden, otherwise return a clear error message.

内容的提问来源于stack exchange,提问作者Rahul Wadhwa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:20:03