ruby-on-rails - 如何从 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) %>
解决方案
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 方式,看看您是否可以解决错误。
推荐阅读
- c# - 使用 IEnumerable ViewModel 在 MVC Razor 视图中呈现下拉列表
- php - 让 laravel 系统在云端运行
- r - 使用 awesomeIcons 更改图标颜色
- jmeter - 没有必填字段的 JMeter 计数器
- python - 使用python的人脸识别错误
- sql-server - 使用 SQL 的 Near By 函数
- django - 发送电子邮件时,Django 会发出信号吗?
- python - Python正则表达式-如何捕获未捕获的其余文本
- sql - 如何从 Sql Server 中的字符串中获取值,
- android - FirebaseRecylcerVAdapter 从最高到最低排序