2011-08-14 33 views
0

如何在my/accounts/page的数据库中显示只有'primary'= true的account.organizations?这是我现在正在尝试的:显示具有特定属性的所有嵌套模型

class Account < ActiveRecord::Base 

    has_many :organizations 
    has_one :primary_organization, 
     :class_name => 'Organization', 
     :conditions => ['primary = ?', true] 

    accepts_nested_attributes_for :organizations 

end 

class Organization < ActiveRecord::Base 

    belongs_to :account 

    has_many :locations 
    has_one :primary_location, 
     :class_name => 'Location', 
     :conditions => ['primary = ?', true] 

    accepts_nested_attributes_for :locations 

end 

Organizations表具有一个带有布尔条目的“主”列。

class AccountsController < ApplicationController 

    def index 
     @accounts = account.organizations.where(:primary => true).all 
    end 

end 

最后是索引视图:

<h1>Account List</h1> 
    <table> 
    <% for account in @accounts %> 
    <tr> 
     <td><%= link_to account.organizations.name if 
         account.organizations.name %></td> 
    </tr> 
    <% end %> 
    </table> 

我目前正在此错误:

NameError in AccountsController#index 

undefined local variable or method `account' for #<AccountsController:0x1e160b0> 
Rails.root: C:/Documents and Settings/Corey Quillen/My  
Documents/rails_projects/shop_manager 

Application Trace | Framework Trace | Full Trace 
app/controllers/accounts_controller.rb:4:in `index' 

任何帮助,这将不胜感激。

回答

0

我看到一些问题。你的第一个问题是,你从来没有在帐户控制器中找到该帐户。这就是为什么你得到你的例外。您需要先加载帐户然后获取其组织。它看起来像你在轨道3,所以你可能想要宣布主要组织的范围。

scope :primary, where(:primary => true) 

如果上述范围的组织类,你可以这样说:

@accounts = Account.find(params[:id]).oranizations.primary 
+0

我加入了范围,但@accounts = Account.find(PARAMS [:编号])。organizations.primary做似乎没有在我的索引行动中工作。为什么我需要包含(params [:id])?网址中没有标识,因为我试图通过http:// localhost:3000/accounts url显示所有主要组织的列表。 –

+0

你想要显示任何帐户的所有主要组织?如果是这样,那么只需使用Organization.primary.all –

+0

不,每个帐户只有一个主要组织。我如何向所有帐户显示所有帐户? –

相关问题