Question

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 :)

Was it helpful?

Solution

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])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top