【发布时间】:2016-02-16 11:26:01
【问题描述】:
使用嵌套表单,我创建了一个按Text1、Url1、Text2 排序的帖子。
但是,当我检索此数据(控制器索引操作)并将其显示在视图中 (index.html.erb) 时,它显示为Text1、Text2、Url1。我怎样才能让它以我在嵌套过帐表单中给出的原始顺序显示在视图中?
您的帮助将是惊人的 - 我就是无法完成这项工作!
后模型
class Post < ActiveRecord::Base
has_many :texts
has_many :urls
accepts_nested_attributes_for :texts, :urls
end
文本模型
class Text < ActiveRecord::Base
belongs_to :post
end
网址模型
class Url < ActiveRecord::Base
belongs_to :post
end
架构
create_table "posts", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "texts", force: :cascade do |t|
t.text "textattr"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "post_id"
end
add_index "texts", ["post_id"], name: "index_texts_on_post_id"
create_table "urls", force: :cascade do |t|
t.string "urlattr"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "post_id"
end
add_index "urls", ["post_id"], name: "index_urls_on_post_id"
帖子控制器
class PostsController < ApplicationController
def index
@posts = Post.includes(:texts, :urls).all.order(created_at: :desc)
end
def show
@post = Post.find(params[:id])
@texts = @post.texts
@urls = @post.urls
@photos = @post.photos
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post
else
render 'new'
end
end
private
def post_params
params.require(:post).permit(:texts_attributes => [:textattr], :urls_attributes => [:urlattr], :photos_attributes => [:image])
end
end
查看(Index.html.erb)
<% @posts.each do |post| %>
<% post.texts.each do |text|%>
<%= text.textattr %> <br>
<% end %>
<% post.urls.each do |url|%>
<%= url.urlattr %> <br>
<% end %>
<% end %>
【问题讨论】:
标签: jquery ruby-on-rails forms ruby-on-rails-4 erb