使用类方法作为范围

时间:2013-07-15 15:11:37

标签: ruby-on-rails

我有一个名为“Project”的模型和一个名为published的类方法?我在哪里确定项目是否已发布。我想基于这个类方法创建一个范围。什么是正确的语法?

这就是我的Project.rb的样子:

class Project < ActiveRecord::Base
  attr_accessible :title, :images_attributes, :ancestry, :user_id, :built, :remix

def published?
    published = false
    if remix_id.blank?
      # check if the remix has been updated
      if updated_at != created_at
        published = true
      end
    else
      # for non remixed projects, projects are published if the title has been updated and a picture has been uploaded
      if title.starts_with("Untitled")
        if images.count > 0
          published = true
        end
      end
    end
  end
  return published
end

我试过了:

scope :published, where(published? => true)

scope :published, where(:published? => true)

1 个答案:

答案 0 :(得分:0)

我想避免为我的Project模型创建一个列,但是我创建了一个名为published的列,并根据已发布的值设置其值?方法。然后我相应地更新列并将其用于范围。