views:

36

answers:

1

Hello again great knowledge masters of stackoverflow, once again the small coder apprentice tabaluga is in need of help

The Goal : make the username sortable in the view. The difficulty is, that I am Querying Profiles in the controller ( Profile.username doesn't exist but Profile.user.username does). How Do I accomplish that? My Code so far

model code

Class User < Activerecord::Base
   attr_accessible :username
   has_one :profile
 end

 Class Profile < Activerecord::Base
   belongs_to :user
 end

controller code

@search = Profile.search(params[:search])

view code

<%= order @search, :by => :user_username %>

okay, the view code doesn't work (obviously) how can I pass the associated object in the view code and convert it to a symbol?

Thanks in advance :)

p.s. EDIT I just figured out, that this code actually works, sorry for bothering :)

+1  A: 

You could try creating a named_scope in your Profile model which sorts the profiles by user before feeding into your search. Something like:

named_scope :sorted_by_user, { :include => :user, :conditions => ["ORDER BY user.username"] }

Then

@search = Profile.sorted_by_user.search(params[:search])
bjg
thanks bjg, the problem with this approach is, that you cannot use the order method in the view, because the order is hardcoded in the named_scope.
tabaluga
@tabaluga OK I see what you're trying to do. The `:by` option just creates some additional GET parameters that the `search` method processes. You pre-parse the `params` in your controller and then call the appropriate `search` variant, with or without the named scope as required.
bjg
great! Everything works! :)
tabaluga