Forum: Ruby on Rails Problems using 'select'

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Domas S. (Guest)
on 2006-05-18 15:35
(Received via mailing list)
I use :filter action to display form and allow record filtering. It
contains form with
combo box, submit button and list of record matching value in combo.

filter.rb:
class Filter
 attr_accessor :owner
  def initialize(params)
  @owner = '';
  if !params[:filter].nil? and params[:filter].has_key?(:owner)
   @owner = params[:filter][:owner]
  end
 end
end

Controler:
@users = User.find_all
@filter = Filter.new(params)

View:
select 'filter', 'owner', @users.collect {|u| [u.name, u.id]},
{:include_blank => true}

My problem is that when I select some "owner" and submit the form
it does not make current owner selected in combo box.
>From Rails documentation I understood that you had to have
@filter.owner = some_value
to make it selected, but it doesn't seem to work. Maybe this is only
for ActiveRecord descendants?

TIA,
Domas S.
Jon M. (Guest)
on 2006-05-18 19:53
This has always worked for me.  Maybe cause of the find method thrown in
there.  i really don't know...


<%= select('filter', 'owner', Users.find(:all, :order => "id
DESC").collect {|p| [ p.name, p.id ] }, {:include_blank => true})  %>

jon
Tom M. (Guest)
on 2006-05-18 20:34
(Received via mailing list)
On May 18, 2006, at 8:53 AM, Jon Mr wrote:

> This has always worked for me.  Maybe cause of the find method
> thrown in
> there.  i really don't know...
>
>
> <%= select('filter', 'owner', Users.find(:all, :order => "id
> DESC").collect {|p| [ p.name, p.id ] }, {:include_blank => true})  %>

I think these snippets of code for select tags make excellent candidates
for helper methods:

{controller|application}_helper.rb

   def users_for_select
     Users.find(:all, :order => "id DESC").collect { |p| [ p.name,
p.id ] }
   end

View:

   <%= select('filter', 'owner', users_for_select, { :include_blank
=> true } %>

Additionally, why sort by id? From a user's perspective, wouldn't
some user
entered value make more sense? Name or email address for instance.

--
-- Tom M.
Domas S. (Guest)
on 2006-05-18 22:13
(Received via mailing list)
As I don't have access to my app from home I'll try to test your
suggestions tomorrow.
Anyway, thanks for help!

Domas S.
Domas S. (Guest)
on 2006-05-19 12:57
(Received via mailing list)
The problem was that @filter.owner was a number, not a string.
So instead:
@owner = params[:filter][:owner]
I wrote:
@owner = params[:filter][:owner].to_i

And it worked.
This topic is locked and can not be replied to.