【问题标题】:undefined method 'each' Ruby on Rails未定义的方法“每个”Ruby on Rails
【发布时间】:2015-10-06 12:46:16
【问题描述】:

提前道歉,我是一个新手,试图让我的头脑绕开轨道。

我在底部的视图在我使用时有效:

def show
@posts = Post.all
end

但是在我的控制器中我现在有:

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

在我看来我有

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

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

【问题讨论】:

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


    【解决方案1】:

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

    Finds the first record matching the specified conditions
    

    find_by_ 将只返回一个帖子,而不是一个集合。所以你不能使用每个。

    【讨论】:

    • 你是最棒的,那个链接正是我需要的。我现在使用@posts = Post.where("category_id = " + params[:id]).all;
    【解决方案2】:

    试试

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

    【讨论】:

    • 为什么是分号? find_by_category_id 自 Rails 4.1 起已弃用,请改用 find_by(category_id: params[:id])
    • 我只是复制粘贴的原始代码,分号在那里,这不是他原来的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 2016-12-15
    • 2019-10-31
    相关资源
    最近更新 更多