显示具有特定属性的所有嵌套模型

时间:2011-08-14 02:23:25

标签: ruby-on-rails ruby-on-rails-3

如何在我/ 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

“组织”表有一个“主”列,它接受一个布尔条目。

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'

对此的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

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

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

如果上述范围在组织类中,您可以这样说:

@accounts = Account.find(params[:id]).oranizations.primary
相关问题