我想删除两个模型 Project 和 Language 之间的关系。这两个模型通过一个链接表链接,该表还存储额外的参数(is_default,...)
我的模型是
class Project < ActiveRecord::Base
has_many :links
has_many :languages, :through => :links
# ...
end
class Link < ActiveRecord::Base
belongs_to :project
belongs_to :language
end
class Language < ActiveRecord::Base
has_many :links
has_many :projects, :through => :links
# ...
end
我在项目控制器中试过这个:
# Removes a languages associated to a project (links table)
def remove_language
lang = current_project.links.where("language_id = ?", params[:id])
current_project.links.delete(lang) if lang
redirect_to project_path(current_project), notice: 'Language has been removed from project.'
end
但我收到以下错误:
ActiveRecord::UnknownPrimaryKey in ProjectsController#remove_language
Unknown primary key for table links in model Link.
我的 routes.rb 包含
resources :projects
match 'projects/remove_language/:id' => 'projects#remove_language'
match 'projects/add_language/:id' => 'projects#add_language'
我用这个打电话给我的控制器:
link_to "Remove", :controller => :projects, :action => :remove_language, :id => a.id