ruby-on-rails - 未定义的方法 'each' Ruby on Rails

标签 ruby-on-rails ruby activerecord model-view-controller

提前道歉,我是一个新手,试图了解 rails 。

当我使用时,底部的 View 可以工作:

def show
@posts = Post.all
end

但是在我的 Controller 中我现在有:

def show
@posts = Post.find_by_category_id params[:id];
end

在我看来,我有

<%= @posts.each do |post| %>
<%= post.title %>
<% end %>

请解释一下为什么我会收到此错误。我应该用什么。 category_id 是 Post 表上的外键。

最佳答案

看看http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find_by

Finds the first record matching the specified conditions

find_by_ 将仅返回一篇文章,而不是一个集合。所以你不能使用每一个。

关于ruby-on-rails - 未定义的方法 'each' Ruby on Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31464935/

相关文章:

ruby-on-rails - 在 Rspec 的 API Controller 测试模块中出现委托(delegate)错误

mysql - 将数据对播种到 Rails 应用程序

mysql - ActiveRecord 为与 MySQL 的 has_and_belongs_to_many 关系生成昂贵的 DESCRIBE 查询

ruby-on-rails - 使用 jQuery 更新 Rails 中的进度条

ruby-on-rails - rails : OR where condition on association

ruby-on-rails - 按月份编号查找特定月份的所有记录(例如 1 = 一月)

ruby - IRB 和大变量?

ruby-on-rails - 新 Rails 安装:ActiveRecord::NoDatabaseError FATAL: role does not exist

ruby-on-rails - 邮箱不发送电子邮件 : wrong number of arguments (1 for 0)

ruby-on-rails - 如何在 Rails 中存储多个可选字段?