2011-08-14 76 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

不,每個帳戶只有一個主要組織。我如何向所有帳戶顯示所有帳戶? –

相關問題