mercredi 2 mars 2016

Rails - Nested Form - Randomise all the individual fields a user posts

A user can create by post, adding as many nested text fields on the fly as they wish by clicking the 'addtext' button [new.html.erb]

If a user, for example, creates a post with three text fields (Text1 Text2 Text3)

http://ift.tt/1LxO6s1

Then another post with three text fields (TextA TextB TextC)

http://ift.tt/1Y1Ph4P

This will currently display in the browser [index.html.erb] as either: http://ift.tt/1LxO8A1 or http://ift.tt/1Y1Pg0P due to .order("RANDOM()") [index action]

However, I am trying to output a randomised list of all the text fields the user posts. For instance, I want to output & randomise over (Text1 Text2 Text3 TextA TextB TextC) in its entirety. In other words, my goal is to output a random assortment of all the text fields individually (TextA Text2 TextC Text1 Text3 TextB)

I can't get this to work via my index action & index.html.erb

Any help would be amazing! Thank you!

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

Schema

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

Aucun commentaire:

Enregistrer un commentaire