如何订购下拉菜单,但在其中随机化?

时间:2014-12-26 23:04:59

标签: ruby-on-rails ruby indexing

我该如何改变:



  def index
    @values = Value.all
  end




...将我的下拉菜单类别以顺序放在索引上

1)Mantra,2)引用,3)原则,4)其他

但是在每个类别中,Value将被随机化,例如Mantra将首先显示在索引中,但在mantra类别中,您键入的咒语将在每次重新加载页面时随机化

value.rb



class Value < ActiveRecord::Base
	belongs_to :user

	VALUES = ['Mantra', 'Quote', 'Principle', 'Other']

end
&#13;
&#13;
&#13;

values_controller.rb

&#13;
&#13;
class ValuesController < ApplicationController
  before_action :set_value, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]

  def index
    @values = Value.all
  end

  def show
  end

  def new
    @value = current_user.values.build
  end

  def edit
  end

  def create
    @value = current_user.values.build(value_params)
    if @value.save
      redirect_to @value, notice: 'Value was successfully created'
    else
      render action: 'new'
  end
end

  def update
    if @value.update(value_params)
      redirect_to @value, notice: 'Value was successfully updated'
    else
      render action: 'edit'
  end
end

  def destroy
    @value.destroy
    redirect_to values_url
  end

  private
    def set_value
      @value = Value.find(params[:id])
    end

    def correct_user
      @value = current_user.values.find_by(id: params[:id])
      redirect_to values_path, notice: "Not authorized to edit this value" if @value.nil?
    end

    def value_params
      params.require(:value).permit(:name, :categories)
    end
end
&#13;
&#13;
&#13;

index.html.erb

&#13;
&#13;
<div id="values" class="transitions-enabled">
  <% @values.each do |value| %>
        <%= value.name %><br/>
        <% if value.user == current_user %>
          <div class="actions">
            <%= link_to edit_value_path(value) do %>
            <b><%= value.categories %></b>
              <span class="glyphicon glyphicon-edit"></span>
            <% end %>
            <%= link_to value, method: :delete, data: { confirm: 'Are you sure?' } do %>
              <span class="glyphicon glyphicon-trash"></span>
            <% end %>
          </div>
        <% end %>
  <% end %>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

问题1: 按自定义顺序订购@values

1)Mantra,2)引用,3)原则,4)其他

我假设这些标签来自name模型的Value属性。要获得此非字母自定义排序,而不必依赖created_at字段进行排序,您需要使用不同的属性进行排序。我将sort:integer属性添加到Value,并使用sort字段的值更新记录:

Value: name: "Mantra", sort: 0
Value: name: "Quote", sort: 1
Value: name: "Principle", sort: 2
Value: name: "Other", sort: 3

然后将您的查询更改为:

@values = Value.order :sort

这将为您提供您指定的订单。现在,为你的下一个问题。我假设你在这个Value模型上有一些关联。你提到过:

  

但在每个类别中

那么每个Value实例都是一个类别?如果您有其他belong_to类别的模型,您可以使用单独的查询来进行排序:

# index action
@categories = Category.order :sort

# then user clicks on a category and they go to its
# show action
@category = Category.find params[:id]
@items = @category.items.order 'RANDOM()'

因此,通过上述内容,在您的类别索引页面上会看到按您的自定义排序排序的类别,然后在点击某个类别(例如Mantra)导航到其展示操作时,他们会看到Mantra类别的项目在每个页面加载的随机顺序。