删除链接表中没有id的has_many through关系

时间:2012-12-20 14:37:38

标签: ruby-on-rails-3 model has-many

我想删除两个模型Project和Language之间的关系。这两个模型通过Link表链接,该表还存储额外的参数(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

我在Project controller中试过这个:

 # 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

1 个答案:

答案 0 :(得分:0)

试试这个:

link = current_project.links.find_by_language_id(params[:id])
link.destroy