mercredi 22 janvier 2020

Rails: find all resources not already connected through join table

I am trying to rewrite actions which connect and disconnect products to and from projects. Currently my select_to_project view shows all products, but I would like it to display only products which have not been already connected to a given project.

Products and projects are connected through a join table

class Product < ActiveRecord::Base
  has_and_belongs_to_many :projects, :join_table => "projects_products"  
end

class Project < ActiveRecord::Base
  has_and_belongs_to_many :products, :join_table => "projects_products" 
end

class ProjectsProduct < ActiveRecord::Base
  attr_accessible :project_id, :product_id

  belongs_to :project
  belongs_to :product
end

In my products controller I currently have:

def select_to_project
  @project = Project.find(params[:id])
  @products = Product.find(:all)
end

def select_from_project
  @project = Project.find(params[:id])
end

Obviously the select_to_project view currently displays all possible products, even those which are already connected through the join table.

I thought the select_to_project action should be changed to something like this:

def select_to_project
  @project = Project.find(params[:id])
  @products = Product.joins(:projects => :products).where('products_projects_join.product_id IS NOT ?', @product)
end

But I currently get an MySQL error when I try to load the relative view:

Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1)' at line 1: SELECT `products`.* FROM `products` INNER JOIN `projects_products` ON `projects_products`.`product_id` = `products`.`id` INNER JOIN `projects` ON `projects`.`id` = `projects_products`.`project_id` INNER JOIN `projects_products` `products_projects_join` ON `products_projects_join`.`project_id` = `projects`.`id` INNER JOIN `products` `products_projects` ON `products_projects`.`id` = `products_projects_join`.`product_id` WHERE (products_projects_join.project_id IS NOT 1)

How can I get this query working in Rails 3?

Thank you very much in advance.

Aucun commentaire:

Enregistrer un commentaire