【问题标题】:In rails, how to destroy a 'join table item' with out deleting the real record?在 Rails 中,如何在不删除真实记录的情况下销毁“连接表项”?
【发布时间】:2011-04-06 00:35:48
【问题描述】:

我现在很困惑,我不知道如何删除/销毁连接表中的记录:


class Task < ActiveRecord::Base
  belongs_to :schema
  belongs_to :to_do
end

class Todo < ActiveRecord::Base
  belongs_to :schema
  has_many :tasks
end

class Schema < ActiveRecord::Base
  has_many :todos
  has_many :tasks, :through => :todos
end

>> sc = Schema.new
>> sc.tasks << Task.new
>> sc.tasks << Task.new
>> sc.tasks << Task.new
...
>> sc.tasks.delete(Task.first) # I just want to delete/destroy the join item here.
# But that deleted/destroyed the Task.first.

如果我只想销毁关系项该怎么办?

【问题讨论】:

    标签: ruby-on-rails join has-many-through destroy


    【解决方案1】:

    如果要删除sc中的所有任务:

    sc.tasks.delete_all
    

    如果要删除 sc 中的特定任务:

    sc.tasks.delete_at(x) where x is the index of the task
    
    or
    
    sc.tasks.delete(Task.find(x)) where x is the id of Task
    

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      如果你想从连接表中删除所有记录,比如amenities_lodgings,而不使用任何你可以使用的对象:

      ActiveRecord::Base.connection.execute("DELETE  from amenities_lodgings")
      

      【讨论】:

        【解决方案3】:

        删除所有加入记录

        如果要删除所有的join记录,可以使用.clear

        >> sc = Schema.new
        >> sc.tasks << Task.new
        >> sc.tasks << Task.new
        >> sc.tasks << Task.new
        >> sc.tasks.size #=> 3
        >> sc.tasks.clear
        >> sc.tasks.size #=> 0
        

        【讨论】:

          猜你喜欢
          • 2015-06-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-18
          • 1970-01-01
          • 1970-01-01
          • 2014-01-22
          相关资源
          最近更新 更多