0

I am having trouble in passing ruby array in sql query. I am using ruby version 2 and rails 4.0.2.

i have a array which contains project names which is passed by the view page and i am reading it through params in my function in the controller.

This is my function :

def fetch_projects()

@projects = params[:projects]

#this is my sql query

@query = " select * from project_view where Projects in '#{@projects.map { |s| s }}'"

@results = ActiveRecord::Base.connection.select_all(@query)

end

I am not able to execute the @query. Thanks in advance

3
  • Do you get any error? Commented Jul 4, 2015 at 8:34
  • Your @query seems wrong. Commented Jul 4, 2015 at 8:42
  • My two cents: It isn't best practices to use raw sql code or reference ActiveRecord::Base directly in a controller. It violates MVC and will make your code difficult to maintain by anyone else. Commented Jul 4, 2015 at 14:12

2 Answers 2

1

Avoid writing raw sql. You are already using a gem called active record that does much more than just running your queries(it keeps it safe to execute & optimizes your queries) and without the hassel of innitiating your connection. You can instead do

ProjectView.where(project: @projects)
Sign up to request clarification or add additional context in comments.

6 Comments

Using Model helped me at some point , thanks :) . But how do i pass an array of projects in the above code of yours . Other then using .each method is there any other way ?
Its Rails syntactic sugar that does that for you..if I understood you correctly the above query is your answer. which would generate a sql query like this 'SELECT * FROM project_view WHERE project_id IN (1,2)'
Assuming your @projects is an array of models rails will automatically generate the array of ids to match by
Hey David Ferd how do i fetch for array of values ? if my @projects contains more then one project name
from your initial query what is the datatype of the field 'Projects'?
|
0
@query = " select * from project_view where Projects in '#{@projects.map { |s| s }}'"

I can see two problems here,

  1. String interpolation does not work with single quetoes. So use #{} directly in the query string.
  2. And your ruby code within string will return Array [1,2,3], so the query fails.

Why don't you try this in Rails way, For ex: ProjectView.joins(:projects).where(projects: {id: @projects.pluck(:id)})

1 Comment

The whole string is enclosed with double quotes, single quotes are just a part of the normal characters in it.

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.