首页 > 解决方案 > 如何从 Rails 中的另一个控制器获取帖子的 ID?

问题描述

我的主要网站是主页/索引。

我想将帖子控制器的内容添加到主控制器中。我想创建一个从主页/索引到帖子/节目的链接。我也在使用脚手架。

但我收到错误找不到带有 'id' = 的帖子

我能做些什么?

home_controller.rb

  def index
    @post = Post.new

    @posts = Post.find(params[:id])
  end

post_controller.rb

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.find(params[:id])
  end

  # GET /posts/1
  # GET /posts/1.json
  def show
  end

  # GET /posts/new
  def new
    @post = Post.new
  end


  # GET /posts/1/edit
  def edit
  end

  # POST /posts
  # POST /posts.json
  def create
    @post = Post.new(post_params)

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /posts/1
  # PATCH/PUT /posts/1.json
  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to @post, notice: 'Post was successfully updated.' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    @post.destroy
    respond_to do |format|
      format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_post
      @post = Post.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def post_params
      params.require(:post).permit(:title, :content)
    end
end

index.html.erb (home_controller)

<%= link_to 'Show', post_path(@posts.id) %>

标签: ruby-on-railsruby

解决方案


index动作通常用于表示项目的集合。例如:

def index
  @posts = Post.order(:published_at).all
end

不过你的index动作看起来很不一样。您正在创建 a 的新实例Post,然后尝试Post按 ID 查找单个实例。这将动作的角色与new动作结合在一起show。例如:

def new
  @post = Post.new
end

def show
  @post = Post.find(params[:id])
end

如果您使用资源丰富的路由,您的路由助手希望您使用这种模式。因此,请求/posts转到 PostsController#index,并/posts/1转到 ID 参数等于 的 PostsController#show 操作1

在您看来,您将链接到index带有posts_path(复数)的show动作和带有post_path(1)(单数,1帖子的 ID 在哪里)的动作。

我建议您检查您的代码并对其进行调整以适应这些最佳实践/ Rails 方式,看看您是否可以解决错误。


推荐阅读