下面是我的index.html.erb(我只想显示品牌和相关子品牌列表)
<h1>Brands</h1>
<% @brands.each do |brand| %>
<h2><%= brand.name %></h2>
<% end %>
<% @brands.subbrands.each do |subbrand| %>
<h2><%= subbrand.name %></h2>
<% end %>
Run Code Online (Sandbox Code Playgroud)
我在查看index.html时收到的错误是:
undefined method `subbrands' for #<Array:0x9e408b4>
Run Code Online (Sandbox Code Playgroud)
这是我的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
Run Code Online (Sandbox Code Playgroud)
这是我的routes.rb
Arbitrary::Application.routes.draw do
resources :brands do
resources :subbrands
end
resources :subbrands do
resources :subsubbrands
end
Run Code Online (Sandbox Code Playgroud)
这是我的brand.rb模型
class Brand < ActiveRecord::Base
validates :name, :presence => true
has_many :subbrands
has_many :subsubbrands, :through => :subrands
end
Run Code Online (Sandbox Code Playgroud)
...和我的subbrand.rb模型
class Subbrand < ActiveRecord::Base
validates :name, :presence => true
belongs_to :brand
has_many :subsubbrands
end
Run Code Online (Sandbox Code Playgroud)
你是这样说的:
@brands = Brand.all
Run Code Online (Sandbox Code Playgroud)
这意味着@brands现在是一个数组,因为all:
一个方便的包装
find(:all, *args).
而且find(:all):
全部查找 - 这将返回所使用选项匹配的所有记录.如果未找到任何记录,则返回空数组.使用
Model.find(:all, *args)或其快捷方式Model.all(*args).
然后你有这个:
<% @brands.subbrands.each do |subbrand| %>
Run Code Online (Sandbox Code Playgroud)
这会产生这个错误:
undefined method `subbrands' for #<Array:0x9e408b4>
Run Code Online (Sandbox Code Playgroud)
因为@brands是Array和Arrays不知道是什么subbrands意思.这样的事情可能会更好:
<% @brands.each do |brand| %>
<% brand.subbrands.each do |subbrand| %>
<h2><%= subbrand.name %></h2>
<% end %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
但是你可能也想用它做点什么brand.
| 归档时间: |
|
| 查看次数: |
350 次 |
| 最近记录: |