【问题标题】:How can I fetch records with avoiding nested nil record?如何在避免嵌套 nil 记录的情况下获取记录?
【发布时间】:2013-01-25 02:48:11
【问题描述】:

我使用acts_as_paranoid 进行逻辑删除。 删除记录时。记录不会消失。它只是在'deleted_at'列中获取时间戳,这意味着已删除。

在我的模型中,

社区 has_many :topics

我获取了所有这样的主题

@topics = Topic.page(params[:page]).order("updated_at DESC")

但是,当它显示其父社区已被删除的主题记录时,它会出现路由错误

如何获取其父“社区”存在的所有主题?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    如果您的社区范围类似于

    class Community
      def self.not_deleted
        where deleted_at: nil
      end
    end
    

    那你就可以了

    @topics = Topic.joins(:community).merge(Community.not_deleted).
      page(params[:page]).order("updated_at DESC")
    

    否则你可以这样做

    @topics = Topic.joins(:community).where( community: { deleted_at: nil } ).
      page(params[:page]).order("updated_at DESC")
    

    【讨论】:

    • 谢谢!我尝试了第一个,它返回此错误:( undefined method `not_deleted'
    • 你必须首先在 Community 类中定义 not_deleted 方法,就像我在示例中所做的那样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多