我想为用户提供一个“随机”选项,以便他们可以从数据库中选择以前创建的日期创意(在letsgos表中)。有一个“让我们去......”部分,用户可以填写表格并提出他们想要继续的日期。将会有用户无法自己提出约会想法。因此,对于那些无法创建自己日期的用户,我想提供一个“随机”按钮,每次点击都会在表单中插入一个日期(来自数据库)。 letgos表中数据库中的日期已分配content
和tag
。当用户点击随机时,它应该使用内容和标记填充表单(每次随机点击应显示数据库中的新数据)。我没有任何javascript经验,所以我不确定我是否采用了正确的方式。
/views/letsgos/_form.html.erb:
<%= form_for(@letsgo) do |f| %>
<div class="field">
<%= f.text_area :content, placeholder: "Propose new date..." %>
</div>
<%= f.select :tag, options_for_select( [["Select One", ""], "Eat/Drink", "Listen/Watch", "Play", "Explore", "Other"]) %>
<a href="/letsgos/random" class="ajax">Click here for a Random letsgo</a>
<%= f.submit "Post" %>
<% end %>
/views/layouts/application.html.erb
<head>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script>
$(document).ready(function() {
$('.ajax').click(function() {
$.get(this.href, function(response) {
console.log(response);
$('body').html(response);
});
});
});
<script>
</head>
letsgo controller:
def create
@letsgo = current_user.letsgos.build(letsgo_params)
if @letsgo.save
flash[:success] = "Date posted!"
redirect_to root_url
else
flash[:error] = "Date was not posted!"
redirect_to root_url
end
end
def destroy
@letsgo.destroy
redirect_to root_url
end
def random
@letsgo = Letsgo.random.first
if request.xhr?
end
end
private
def letsgo_params
params.require(:letsgo).permit(:content, :tag)
end
def correct_user
@letsgo = current_user.letsgos.find_by(id: params[:id])
redirect_to root_url if @letsgo.nil?
end
缓存列迁移:
rails g migration add_ids_count
def self.up
add_column :letsgos, :ids_count, :integer, :default => 0
Letsgo.reset_column_information
Letsgo.all.each do |l|
l.update_attribute :id_count, l.id.length
end
end
def self.down
remove_column :letsgos, :id_count
end
end
答案 0 :(得分:3)
如果您担心Antarr Byrd建议的表现,那么创建一个解决方案就是设置一个缓存列来存储Letsgo
的ID数组。基本上,这会将Letsgo.pluck(:id)
缓存在DB中的单个列中。 (也许在Letsgos上的后保存和/或后删除钩子中的工作人员中这样做。)我建议在某种缓冲区中执行此操作,或者可能作为每小时任务。
然后,您可以将其作为JavaScript数组(示例中为letsgos_ids_array
)拉入,并根据该数组的长度创建Math.random()值并将其发送到.find()。当然你也可以直接输出数组的长度。
var item_index = Math.floor(Math.random() * letsgos_ids_array_length);
$.get("/letsgos/random", {
"ind" : item_index
}, function(data){
/* do something with the data */
});
然后,此索引可用于从db中提取数组中的实际ID值。
letsgoarray = Letsgosarray.first # this is the single-column "cached" array of IDs
item_id = letsgosarray[params[:id_index]]
@random_letsgo = Letsgos.find(item_id)
format.json do {
render json: @random_letsgo
}
数组访问速度很快,单个数据库列查询也是如此。
答案 1 :(得分:1)
这里有一些关于随机行的好读物:
答案 2 :(得分:0)
我从来没有这样做,但你可以做到
def random
Letsgos.find(Letsgo.pluck(:id).sample)
end