Rails API项目需求:获取特定ID数据而非全部数据
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 thanfind(params[:id])because it avoids raising an exception if the post doesn't exist.- We use
exists?instead ofpluckfor 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

