Part of my RoR application is responsible for managing web site designs portfolio. One web site design can have many images associated with it. One image can be associated only with one design. I use has_many statement with :through parameter to connect images with design through join table. And when image is deleted associated entry in join table must be deleted. So i have next models For images:
class Image < ActiveRecord::Base
has_one :images_site_designs , :class_name => "ImagesSiteDesigns" , :dependent => :destroy
has_one :site_design , :through => :images_site_designs
end
For site_designs:
class SiteDesign < ActiveRecord::Base
belongs_to :client
has_many :images_site_designs , :class_name => "ImagesSiteDesigns"
has_many :images , :through => :images_site_designs
end
And join table images_site_designs:
class ImagesSiteDesigns < ActiveRecord::Base
belongs_to :image
belongs_to :site_design
end
Creating new images for site_designs is ok, so folowing code works fine:
@site_design = SiteDesign.find(params[:id])
@site_design.images << Image.new(params[:image])
But when i try to delete image next error appears:
ActiveRecord::StatementInvalid in ImagesController#destroy
Mysql::Error: Unknown column 'id' in 'where clause': DELETE FROM `images_site_designs` WHERE `id` = NULL
It seems that rails use wrong column name for querying images_site_designs join table. How can i fix it?
upd:
image_controller functions that deletes image:
def destroy
@image = Image.find(params[:id])
@image.destroy
respond_to do |format|
format.html { redirect_to(images_url) }
format.xml { head :ok }
end
end
migrations:
class CreateImages < ActiveRecord::Migration
def self.up
create_table :images do |t|
t.string :url
t.string :name
t.text :description
t.timestamps
end
end
def self.down
drop_table :images
end
end
class CreateSiteDesigns < ActiveRecord::Migration
def self.up
create_table :site_designs do |t|
t.string :name
t.text :concept
t.text :description
t.integer :client_id
t.timestamps
end
end
def self.down
drop_table :site_designs
end
end
class CreateImagesSiteDesigns < ActiveRecord::Migration
def self.up
create_table :images_site_designs , :id => false do |t|
t.integer :image_id
t.integer :site_design_id
end
end
def self.down
drop_table :images_site_designs
end
end