我正在构建一个页面,该页面将列出所有包含 :category_id 值“1”的模型,这是页面本身的片段
<h1>Discover the best of Games</h1>
<p>These are games we have featured and awarded</p>
<% @posts.find_by(category_id: 1) do |post| %>
<h2>
<%= link_to post.title, post %>
</h2>
<% end %>
注意@posts.find_by(category_id: 1) 做 |post|显然是错误的。它没有显示任何帖子,并且出现了 undefined method
find_by' for nil:NilClass` 的错误 所以是的,我知道 .find_by 是不正确的。这是显而易见的。
这是来自 Schema.rb 和 post_controller.rb 的片段
架构
create_table "categories", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "category_id"
end
add_index "posts", ["category_id"], name: "index_posts_on_category_id"
Posts_controller(整个事情)
class PostsController < ApplicationController
before_action :find_post, only: [:show, :edit, :update, :destroy]
def index
@posts = Post.all.order("created_at DESC")
end
def show
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post, notice: "Successfully created"
else
render 'new'
end
end
def edit
end
def update
if @post.update(post_params)
redirect_to @post, notice: "Post was successfully updated"
else
render 'edit'
end
end
def destroy
@post.destroy
redirect_to root_path
end
private
def post_params
params.require(:post).permit(:title, :description, :category_id)
end
def find_post
@post = Post.find(params[:id])
end
end
任何帮助将不胜感激,因为我是 Rails 的新手并且刚刚掌握基础知识。谢谢。
最佳答案
编辑:
Post.where(category_id: 1)
所以:
<% Post.where(category_id: 1).each do |post| %>
<h2>
<%= link_to post.title, post %>
</h2>
<% end %>
find_by
更适用于需要单个对象的情况。如果您想要一组基于一组条件的对象,请使用 where。此外,find_by
可以根据您的模型具有的字段解析诸如 find_by_category_id
之类的方法,因此 Post.find_by_title
和 Post.find_by_description
会神奇地工作。同样,在这些情况下我会使用 where
,但只是为了引用而注明。
做同样事情的另一种方法,假设你的模型设置正确,将是:
Category.find(1).posts
这将列出类别 1 中的所有帖子。这可能比 Post.where
更明确,并且此版本的优点是如果有关于类别的信息,您希望在页面,例如类别名称。那么你已经有了这个对象:
@category = Category.find(1)
@posts = @category.posts
<h1>Posts for <%= @category.name %></h1>
<% @posts.each do |post| %>
... you know the rest
无论如何,希望这能让事情在如何组合和工作方面变得更清楚一些。
关于ruby-on-rails - 有人会如何列出在 Ruby on Rails 中具有特定值的所有对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35856681/