开发者

Displaying all nested models with a specific attribute

How do I show only account.organizations with 'primary' = true in the database on my /accounts/ page? Here is what I am trying now:

class Account < ActiveRecord::Base

    has_many :organizations
    has_one :primary_organization,开发者_JS百科
        :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

The Organizations table has a 'primary' column that takes a boolean entry.

class AccountsController < ApplicationController

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

end

And lastly the index view:

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

I am currently getting this error:

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'

Any help with this will be greatly appreciated.


I see a few problems. Your first issue is that you never find the account in your accounts controller. Thats why you get the exception you have. You need to first load the account and then get its organizations. It looks like you are on rails 3 so you may want to declare a scope for the primary organizations.

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

If the above scope is in the Organization class you can say this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜