Binding Variables in Ruby
I currently have a table that is listed as follows:
projects = Project.find(:all, :conditions => [conditions + "AND (name LIKE ? OR description LIKE ?)", "%#{params[:query]}%", "%#{params[:query]}%"])
where
conditions = Project.in_used_project开发者_开发知识库s(:alias => "projects")
However I need to include a 3rd variable which is not from the Project table but from a Tags table. The column I need is Tag - > Names
. Is there anyway I can bind variables from another table in Ruby? The Project.find(all)
automatically passes the SELECT * FROM Project
into MYSQL. Someone has suggested using a join function, but I'm not sure how this would work. Any ideas?
EDIT 1
I have tried the suggested answer of using
projects = Project.find(:all, :joins => "tags", :conditions => [conditions + "AND (projects.name LIKE ? OR description LIKE ? OR tags.name LIKE ?", ["%#{params[:query]}%" * 3]].flatten)
but now I am getting another error
Mysql::Error: Unknown table 'projects': SELECT
projects.* FROM
projectstags WHERE ((projects.status = 2)AND (projects.name LIKE '%%' OR projects.description LIKE '%%' OR tags.name LIKE '%%')
Very strange considering the projects table exists. Why isn't Ruby recognizing it now that i've included another table?
Try this out for size:
projects = Project.find(:all, :joins => "tags", :conditions => [conditions + "AND (projects.name LIKE ? OR description LIKE ? OR tags.name LIKE ?", ["%#{params[:query]}%" * 3]].flatten)
The :joins
option tells Active Record to perform an SQL join onto the tags
table, which will allow you to perform queries on the tags column. Also take note in this example how I've added the projects.
prefix to your original name
column. This is so your database doesn't get confused what name
column you want; the one from the projects
or the tags
table.
Do you have any relationship between projects and tags? If the reason for your query is that there is, it should be reflected in the model (for ex with a HABTM), which would also enable you to easily filter based on that relationship without the need to have complex SQL queries crafted.
Turns out that it was just a simple syntax error
projects = Project.find(:all, :joins=>:tags, :conditions => [conditions + "AN rojects.name LIKE ? OR projects.description LIKE ? OR tags.name LIKE ?)", "%# ams[:query]}%", "%#{params[:query]}%", "%#{params[:query]}%"])
is the correct syntax. The :joins needs to be followed by :tags, not by "tags" Thanks again for everyone's help
精彩评论