簡體   English   中英

如何訂購一個下拉菜單,但在其中隨機化?

[英]How to Order a Drop-Down Menu, but Randomize Within It?

我該如何更改:

  def index @values = Value.all end 

...將使我的下拉菜單類別按此順序放在索引上

1)口頭禪,2)報價,3)原理,4)其他

但是在每個類別中,值將被隨機化,例如,Mantra將首先出現在索引中,但是在mantra類別中,您鍵入的咒語將在每次重新加載頁面時隨機化

value.rb

 class Value < ActiveRecord::Base belongs_to :user VALUES = ['Mantra', 'Quote', 'Principle', 'Other'] end 

values_controller.rb

 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 

index.html.erb

 <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> 

問題1:以自定義順序對@values進行排序:

1)口頭禪,2)報價,3)原理,4)其他

我假設這些標簽來自您的Value模型的name屬性。 為了獲得這種非字母的自定義排序,並且不必依賴created_at字段進行排序,您需要一個不同的屬性進行排序。 我將為Value添加一個sort:integer屬性,並使用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一個類別的模型, 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()'

因此,使用上面的內容,在類別索引頁面上會看到按您的自定義順序排序的類別,然后,在單擊類別(例如,咒語)以導航至其顯示操作時,他們將以隨機的順序看到咒語類別的項目每個頁面加載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM