Topic: Change scope and results via Ajax

I have a Page (model/controller/view) that pulls together a lot of different data. One part of that data is the current_user's accounts, which have_many items. When home/index is first shown, I'm defaulting to the first Account the user has, and the associated Items:

[in home/index]
@account = current_user.acounts.find(:first)
@items = @acount.items

What I want to do is have a dropdown (select_tag) that lists all of the user's accounts. When the user picks from that list, the items shown refreshes to those of that account.

How do I pass back from the select_tag to the controller, then set the @account to the right id? Ideally, I want to replace the items with the items from the selected account, but I'm trying to get my head around how to set the id of the current account...

Re: Change scope and results via Ajax

Here, I explain the breakdown of how you can remotely call controller methods: http://railsforum.com/viewtopic.php?id=47873

If you have a custom method inside of your controller, such as:
Account.rb

def ajax_user user_id
  @account = current_user.accounts.find(user_id)

  respond_to do |format|
    format.js   { render :partial => '[b]view/directory/return_file[/b]', :locals => {:account => @account, :items = @account.items}, :content_type => 'text/html' }
  end

Now, inside your /views/directory/_return_file.html.erb file, simply layout the information you would like to return.

Also, since ajax_user is a custom method, the application will not recognize it in the routes. So you will need to change your route information from:

  resources :accounts

to

  resources :accounts do
    put 'ajax_user', :on => :member
  end

I hope that all makes sense and leads you in the right direction

Remember to edit your topic title and add "[SOLVED]" if your question has been answered!

Follow me!