Rails - 嵌套表单 - 随机化用户发布的所有单个字段

时间:2016-03-02 16:43:37

标签: jquery ruby-on-rails ruby sqlite ruby-on-rails-4

用户可以通过发布创建,通过点击“添加文字”来随时添加尽可能多的嵌套文本字段。按钮[ new.html.erb ]

例如,如果用户创建了包含三个文本字段的帖子 ( Text1 Text2 Text3

enter image description here

然后另一篇文章有​​三个文本字段 ( TextA TextB TextC

enter image description here

这将显示在浏览器[ index.html.erb ]中:http://imgur.com/Nd0Erybhttp://imgur.com/rl0m60U由于.order(" RANDOM() ")[索引操作]

但是,我正在尝试输出用户发布的所有文本字段的随机列表。例如,我想输出&完整地随机化( Text1 Text2 Text3 TextA TextB TextC )。换句话说,我的目标是单独输出所有文本字段的随机分类( TextA Text2 TextC Text1 Text3 TextB

我无法通过索引操作&的 index.html.erb

任何帮助都会很棒!谢谢!

new.html.erb

<button id='addtext'>text</button>

<%= form_for @post, html: { multipart: true } do |f| %>
 <%= f.fields_for :things do |ff| %>
 <% end %> 
  <%= f.submit %>
<% end %>

posts_controller.rb

class PostsController < ApplicationController

  def index
     @posts = Post.includes(:things).all.order("RANDOM()")
  end 

end

index.html.erb

<@posts.each do |post| %>
 <% post.things.each do |thing| %>

  <%= thing.try(:text) %>

 <% end %>
<% end %>

架构

ActiveRecord::Schema.define(version: 20160227154831) do

create_table "posts", force: :cascade do |t|
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
end

create_table "taggings", force: :cascade do |t|
 t.integer  "tag_id"
 t.integer  "taggable_id"
 t.string   "taggable_type"
 t.integer  "tagger_id"
 t.string   "tagger_type"
 t.string   "context",       limit: 128
 t.datetime "created_at"
end

  add_index "taggings", ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true
  add_index "taggings", ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context"

create_table "tags", force: :cascade do |t|
 t.string  "name"
 t.integer "taggings_count", default: 0
end

add_index "tags", ["name"], name: "index_tags_on_name", unique: true

create_table "things", force: :cascade do |t|
 t.text     "text"
 t.integer  "post_id"
 t.datetime "created_at",         null: false
 t.datetime "updated_at",         null: false
 t.integer  "order"
end

end

3 个答案:

答案 0 :(得分:1)

不确定我是否理解正确,但如果您想要当前用户的所有内容,随机排序,这将有效:

class PostsController < ApplicationController
  def index
    @things = Thing.joins(post: :user).where(users: { id: current_user.id }).order("RANDOM()")
  end 
end

在DB中进行随机排序(随机排序)也比在ruby中改组更好,因为它更快。

编辑:更优雅的是,你可以添加一个has_many:through关系,以便能够通过执行current_user.things直接访问current_user的东西。但是我把这个练习留给你......; - )

答案 1 :(得分:0)

你试过这个吗?

class PostsController < ApplicationController

  def index
     @posts = Post.includes(:things).find(:all, :order =>"RANDOM()", :limit => 10)
  end 

end

MySQL也使用RAND()而不是RANDOM()。

答案 2 :(得分:0)

你可以尝试以下
posts_controller.rb

   class PostsController < ApplicationController

    def index
      @things = Thing.all
    end 

   end
index.html.erb中的

    <% @things.shuffle.each do |thing| %>

     <%= thing.try(:text) %>

   <% end %>