Forum: Ruby on Rails re-factoring common sql

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.
cole.jeff (Guest)
on 2005-11-20 20:50
(Received via mailing list)
I would like to Not Repeat Myself (tm) and re-factor frequently-used
SQL into some kind of attribute. For example, instead of re-writing
the "visible" conditions each time:

   def find_by_name(name)
       User.find(:first, :conditions=>["visible = true and name = ?",
name])
   end

   def find_by_login(login)
      User.find(:first, :conditions=>["visible=true and login=?",
login])
   end

I would like to instead skip the visible SQL each time and do
something like this:

   User.visible.find(:first, :conditions=>["name = ?", name])
   User.visible.find(:first, :conditions=>["login=?", login])

This is a contrived example I just made up, but is this possible?

thanks,
Jeff
rails_lists (Guest)
on 2005-11-20 21:23
(Received via mailing list)
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Jeff,

What about defining another method that tacked on "visible = true"

def find_visible(*args)
   args[:conditions] << " AND visible = true"
   User.find args
end

def find_by_name(name)
   User.find_visible :first, :conditions => ["name = ?", name]
end

That answer feels weak, but maybe it'll get you headed in the right
direction.

- --Jeff

On Nov 20, 2005, at 10:46 AM, Jeff C. wrote:

>      User.find(:first, :conditions=>["visible=true and login=?",
>
> thanks,
> Jeff
> _______________________________________________
> Rails mailing list
> removed_email_address@domain.invalid
> http://lists.rubyonrails.org/mailman/listinfo/rails

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (Darwin)

iD8DBQFDgM0IG9xIoXK+giARAheWAJ0U8DkMXMrkyLobbux5qs5cm0PbQwCfVyzr
sWY1lc4jYfpLEdqD1IyaGg8=
=BBbb
-----END PGP SIGNATURE-----
rails_lists (Guest)
on 2005-11-20 21:27
(Received via mailing list)
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

oop!

Probably have to look more like

args[:conditions][0] << " AND visible = true"

On Nov 20, 2005, at 11:22 AM, Jeff S. wrote:

> end
> On Nov 20, 2005, at 10:46 AM, Jeff C. wrote:
>>   def find_by_login(login)
>> This is a contrived example I just made up, but is this possible?
>
> iD8DBQFDgM0IG9xIoXK+giARAheWAJ0U8DkMXMrkyLobbux5qs5cm0PbQwCfVyzr
> sWY1lc4jYfpLEdqD1IyaGg8=
> =BBbb
> -----END PGP SIGNATURE-----
> _______________________________________________
> Rails mailing list
> removed_email_address@domain.invalid
> http://lists.rubyonrails.org/mailman/listinfo/rails

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (Darwin)

iD8DBQFDgM2cG9xIoXK+giARAhShAKCeYEPXdNxEJyBHZmyHFUZei2x8TQCg2sa0
euB1y/r0MYsRHOVt5yx/h9w=
=JhYu
-----END PGP SIGNATURE-----
This topic is locked and can not be replied to.