0

だから私は、ユーザーが私のビューのリンクからレシピの配列をソートできるようにしようとしています:

<%= link_to "Score", recipes_sort_path, :order => 'score' %>

パラメータ「score」をコントローラーメソッド「sort」に送信します。これは次のようになります。

  def sort
    if (params[:order] == 'score')
      @recipes.sort_by(&:score)
    end

    respond_to do |format|
      format.html { redirect_to recipes_path }
      format.json { render json: @recipe }
    end
  end

次の index メソッドにリダイレクトします。

  def index
    # If recipes already present, skip following
    if (!@recipes)
      if (params[:search] || params[:tag])
        @recipes = Recipe.search(params[:search], params[:tag])
      else
        @recipes = Recipe.all
      end
    end

    respond_to do |format|
      format.html 
      format.json { render json: @recipe }
    end
  end

アイデアは、並べ替えられたリストを使用してインデックス ビューにリダイレクトされ、ビューをレンダリングするだけでした。エラーは発生しませんが、リンクをクリックするとページがリロードされますが、何も起こりません。

Recipe クラスは次のようになります。

class Recipe < ActiveRecord::Base
  attr_accessible :instructions, :name, :slug, :score, :upvotes, :downvotes, :comments, :image

  has_and_belongs_to_many :ingredients
  has_and_belongs_to_many :tags
  has_many :comments  
  belongs_to :user
  delegate :name, :to => :user, :prefix => :user, :allow_nil => true
  mount_uploader :image, ImageUploader

  validates :name, :presence => true

  def score
    score = (self.upvotes - self.downvotes)
  end
end

ここで何が間違っていますか?

4

2 に答える 2

2

3番目のオプションがあります(最初の2つはckruseの回答からのものです)。並べ替えアクションからインデックス テンプレートをレンダリングできます

def sort
  if (params[:order] == 'score')
    @recipes.sort_by!(&:score)
  end

  respond_to do |format|
    format.html { render :index }
    format.json { render json: @recipe }
  end
end

これは、並べ替えアクションで @recipes を使用している間、index テンプレートを使用します。また、リダイレクトしていないため、1 つの要求を保存します。

私がコメントしたいもう1つのことは、リンクです。そのはず

<%= link_to "Score", recipes_sort_path(:order => 'score') %>

更新: @recipes を取得しています。可能な限り、SQL にソートを実行してもらいたいので、ここではそのようにします。

def sort
  @recipes = Recipe

  if params[:order] == 'score'
    @recipes = @recipes.order('upvotes - downvotes')
  end

  respond_to do |format|
    format.html { render :index }
    format.json { render json: @recipe }
  end
end
于 2013-02-22T12:49:46.857 に答える
0

まず、sort_by「破壊的」ではなく、新しい配列を返します。の戻り値をに使用sort_by!または保存することができます。sort_by@recipes

sort2 番目:アクションで何もレンダリングしません。すべてのコードを投稿した場合でも、@recipes空です。次の 2 つのことを行うことができます。

  • sortメソッドで行ったように、メソッドでデータを取得してindexから呼び出しますrender :index
  • メソッドをソートし、indexメソッドをまったく使用しないでくださいsort。複数の URI を同じアクションにルーティングできます。
于 2013-02-22T12:23:53.170 に答える