2012-08-01 89 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