开发者

rails run function inside query

If I have the following query, is it possible to be able to run a function inside? Let's say I want to add WHERE zip_code = user_distance(zip_code)?

I want to take data from each row and run it through a function before actually selecting it.

@posts = Listing.find_by_sql(["SELECT * FROM listings WHERE industry = ? &a开发者_开发百科mp;& ", current_user.industry])


If you are mainly looking to get this working and not worrying so much about performance (because going straight to the SQL is faster than going through ActiveRecord) then you could do:

listings = []
Listing.all.each do |listing|
    listings << listing if user_distance(listing.zip_code)
end

So, it will go through each listing and add it to that array if the user_distance method returns true (or however it is set up).

Another thing you could do is set up a stored procedure ("stored proc") on your database that takes in a zip code and returns what it is you want (i.e, does the same thing as user_distance), and that user defined variable max_distance could be in a database table so it's accessible to your stored procedure. Then you could call that stored proc from the SQL and still be able to pass in the zip_code of each row.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜