2016-02-15 26 views
0

我正在嘗試創建發佈表單來發布url &一些文本。嵌套表單提交時沒有錯誤,但我無法在show動作控制器中顯示該表單的後續內容。Rails一對多嵌套表單 - 使用控制器顯示操作查看發佈表單時出錯?

郵政型號

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 

柱控制器

class PostsController < ApplicationController 

    def index 
     @posts = Post.all 
    end 

    def show 
    @post = Post.find(params[:id]) 
    @texts = @post.texts 
    @urls = @post.urls 
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]) 
    end 

show.html.erb

<%= @text.textattr %> 
    <%= @url.urlattr %> 

數據庫架構

 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" 

    end 

錯誤消息後,我按提交表單 上(http://imgur.com/dzdss5z

你的幫助將是驚人的 - !謝謝!

回答

0

@text@url變量從未在控制器的show動作中設置,因此它們爲零。因此,當您嘗試在視圖中調用這些屬性時會出錯。

您已設置@texts@urls變量,所以你可以做這樣的事情:

<% @texts.each do |text| %> 
    <%= text.textattr %> 
<% end %> 

<% @urls.each do |url| %> 
    <%= url.urlattr %> 
<% end %> 
+0

MASSIVE謝謝!英雄 – domburford

相關問題