未定义的方法 [英] Undefined method

查看:47
本文介绍了未定义的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的 index.html.erb(我只想显示一个品牌和相关子品牌的列表)

Below is my index.html.erb (I just want to show a list of Brands and associated Subbrands)

<h1>Brands</h1>

<% @brands.each do |brand| %>
<h2><%= brand.name %></h2>
<% end %>

<% @brands.subbrands.each do |subbrand| %>
<h2><%= subbrand.name %></h2>
<% end %>

我在查看 index.html 时收到的错误是:

The error I receive when viewing index.html is:

undefined method `subbrands' for #<Array:0x9e408b4>

这是我的brands_controller:

Here is my brands_controller:

class BrandsController < ApplicationController

def index
  @brands = Brand.all

  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @brands }
  end
 end

end

这是我的routes.rb

Here is my routes.rb

Arbitrary::Application.routes.draw do

resources :brands do
  resources :subbrands 
  end

resources :subbrands do
   resources :subsubbrands
  end

这是我的brand.rb模型

Here is my brand.rb model

class Brand < ActiveRecord::Base
    validates :name, :presence => true

    has_many :subbrands
    has_many :subsubbrands, :through => :subrands
end

...还有我的 subbrand.rb 模型

...and my subbrand.rb model

class Subbrand < ActiveRecord::Base
    validates :name, :presence => true

    belongs_to :brand
    has_many :subsubbrands
end

推荐答案

你是说:

@brands = Brand.all

这意味着 @brands 现在是一个数组,因为 all:

That means that @brands is now an Array because all:

find(:all, *args) 的便利包装器.

find(:all):

查找全部 - 这将返回与所用选项匹配的所有记录.如果没有找到记录,则返回一个空数组.使用 Model.find(:all, *args) 或其快捷方式 Model.all(*args).

Find all - This will return all the records matched by the options used. If no records are found, an empty array is returned. Use Model.find(:all, *args) or its shortcut Model.all(*args).

然后你有这个:

<% @brands.subbrands.each do |subbrand| %>

这会产生这个错误:

undefined method `subbrands' for #<Array:0x9e408b4>

因为 @brands 是一个数组,而数组不知道 subbrands 是什么意思.像这样的事情可能会更好:

Because @brands is an Array and Arrays don't know what subbrands means. Something like this might work better:

<% @brands.each do |brand| %>
    <% brand.subbrands.each do |subbrand| %>
        <h2><%= subbrand.name %></h2>
    <% end %>
<% end %>

但您可能也想对 brand 做点什么.

But you probably want to do something with the brand too.

这篇关于未定义的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆