alterpub
alterpub

Reputation: 401

Select from database in rails3

I can't get clean results from database,

module PagesHelper
    def list
        wishes = WishList.select("content").where("user_id = #{@user.id}")      
        wishes.each do |wish|                                                   
            puts wish.fetch_hash                                                
        end                                                                     
    end                                                                         
end  

results for user with id 6:

[#<WishList content: "test3">, #<WishList content: "test4">, #<WishList content: "test5">]

but i want to get list like: test3, test4, test5 without flood, how i can get it ?

Upvotes: 1

Views: 550

Answers (2)

Ryan Bigg
Ryan Bigg

Reputation: 107728

First, never ever ever interpolate values into where. This can lead to SQL injection of parameters. For example, this is bad:

WishList.select("content").where("user_id = #{@user.id}")

And this is OK:

WishList.select("content").where(:user_id => @user.id)

This will automatically escape the @user.id portion of the query, which there isn't really a need for in in this query, but imagine you were doing something like this:

User.select("email, password").where("admin = #{params[:admin]}")

Then anybody could pass through any value in params[:admin] they want.

So.


Anyway, access it through an association:

wishes = @user.wishlist.select("content") 

Then as Carl Lazlo recommended:

wishes.map(&:content)

Upvotes: 2

Yann Marquet
Yann Marquet

Reputation: 69

Instead of:

wishes.each do |wish|                                                   
  puts wish.fetch_hash                                                
end

Do:

wishes.map(&:content)

Upvotes: 1

Related Questions