0

I need to test if an instance variable in my controller contains a specific value. I think .include? would be the way to do it but that doesn't seem to work.

My code looks something like this:

@names=Model.find_by_sql("select name from ...") 

if @names.include?(params[:name]) 
    ...
end

The if statement somehow allways evaluates to true.

Thanks

0

2 Answers 2

5

Firstly, find_by_sql is not a good way to do. find_by_sql will return you an object of class Model. Whereas params[:name] is most likely a string. The following should work:

Model.find(:all, :conditions => 'specify conditions here').map(&:name).include?(params[:name])
Sign up to request clarification or add additional context in comments.

2 Comments

I changed the code to: @names=Model.find(:all, :conditions => '...').map(&:name) if @names.include?(params[:name]) but the .include? allway evaluates to false?
You should use a debugger to check the values of @names and params[:name]. I'm pretty sure if the array contains the same name as in params[:name], it would return true.
0

The results of find_by_sql will be (from the docs):

an array with columns requested encapsulated as attributes of the model you call this method from.

You need to search within the results.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.