2012-08-01 100 views
0

在我的論壇中,reply_to和帶引號的變量被傳遞到新的帖子頁面,非常好地回覆和引用。問題出現在用戶做錯事的時候;例如,如果帖子太短,則控制器呈現「帖子/新帖子」並出現閃光錯誤。渲染模板時傳遞變量

我不能爲了我的生活讓控制器在渲染時傳遞這些信息。這是我的設置。

兩個變量初始化新方法:

def new 
    @post = Post.new 

    init_quoted 
    init_reply_to 

    if @quoted 
    @post.content = "[quote="[email protected]+"]"[email protected]+"[/quote]" 
    end 
end 

def init_reply_to 
    if params[:reply_to] 
    @reply_to = Discussion.find(params[:reply_to]) 
    end 
end 

def init_quoted 
    if params[:quoted] 
    @quoted = Post.find(params[@quote]) 
    end 
end 

這當用戶不犯錯誤的偉大工程。然而,從以下代碼中的「其他」開始,變量沒有通過:

def create 
    @post = current_user.posts.build(params[:post]) 

    if @post.save 
    flash[:success] = "You reply has been added." 
    redirect_to controller: 'discussions', action: 'show', id: @post.discussion.id, anchor: 'post'[email protected]_s 
    else 
    render template: 'posts/new', locals: { reply_to: @reply_to, quoted: @quoted } 
    end 
end 

我是否錯過了什麼?變量應該是全球性的,爲什麼他們不被轉移?

回答

1

嗯,你不打電話給你的初始化函數在create

這應該工作:

def create 
    @post = current_user.posts.build(params[:post]) 

    if @post.save 
    flash[:success] = "You reply has been added." 
    redirect_to controller: 'discussions', action: 'show', id: @post.discussion.id, anchor: 'post'[email protected]_s 
    else 
    init_quoted 
    init_reply_to 
    render template: 'posts/new' 
    end 
end 

無需指定他們爲當地人,只是訪問它們的@quoted@reply_to視圖

+0

不幸的是,這是行不通的。它仍然像變量沒有被定義一樣,給出一個錯誤頁面抱怨其中一個變量爲零。 – 2012-08-01 20:29:33

+0

好吧,那是因爲你的初始化函數需要特定的參數才能從數據庫中獲取值...確保你在創建操作中具有所需的參數以從數據庫中獲取它們! – 2012-08-01 20:31:57

+0

這裏已經很晚了,我有一點心理障礙......我怎樣才能將變量傳輸到創建動作?它們通過URL變量(例如,/ posts/new?quoted = 11&reply_to = 8)被引入到新動作中。 – 2012-08-01 20:37:15