0

ユーザーが index アクションを使用すると、質問のリストが表示されます。このリストをフィルタリングして、却下された質問、画像のみが添付された質問などを表示したいと考えています。

どうやってそれをしますか?別の名前付きパラメーターが要求パラメーター ハッシュに含まれているかどうかを確認するコードをインデックス アクションに追加し、それらを使用してクエリを作成しますか。

myurl.com/questions?status=approved&only_images=yes

それとももっと良い方法がありますか?

4

3 に答える 3

3

has_scopeを使用してこれをエレガントに行うことができます。

# Model
scope :status, proc {|status| where :status => status}
scope :only_images, ... # query to only include questions with images

# Controller
has_scope :status
has_scope :only_images, :type => boolean

def index
  @questions = apply_scopes(Question).all
end
于 2012-08-10T08:07:44.133 に答える
1

コントローラーを薄く保ち、スパゲッティ コードを回避するには、次の方法を試してください。

コントローラ:

def index
  @questions = Question.filter(params.slice(:status, :only_images, ...) # you still can chain with .order, .paginate, etc
end

モデル:

  def self.filter(options)
    options.delete_if { |k, v| v.blank? }
    return self.scoped if options.nil?
    options.inject(self) do |scope, (key, value)|
      return scope if value.blank?
      case key
        when "status" # direct map
          scope.scoped(:conditions => {key => value})
        when "only_images"
          scope.scoped(:conditions => {key => value=="yes" ? true : false})
        #just some examples
        when "some_field_max"
          scope.scoped(:conditions => ["some_field <= ?", value])
        when "some_field_min"
          scope.scoped(:conditions => ["some_field >= ?", value])
        else # unknown key (do nothing. You might also raise an error)
          scope
      end
    end
  end
于 2012-08-10T07:53:52.850 に答える
0

ですから、そのようなシナリオで適切にコーディングする必要がある場所があると思います。モデルとコントローラー。

モデルにはスコープを使用する必要があります。

#Model
scope :rejected, lambda { where("accepted = false") }
scope :accepted lambda { where("accepted = true") }
scope :with_image # your query here

コントローラーでは、

def index
  @questions = @questions.send(params[:search])
end

UI からメソッド名を送信し、それをモデルのスコープに直接渡すことができます。また、UI から再度渡すことで、.all ケースの「if」条件を回避できます。

ただし、これは Model コードをビューに直接公開するため、before_filter を使用してコントローラーのプライベート メソッドでビューから来る不要なフィルター パラメーターをフィルター処理する必要があります。

于 2012-08-10T09:56:01.273 に答える