ruby-on-rails - 如何在 Rails 中的渲染 Action 中传递参数

标签 ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2 render

def create
    @emppede = Emppede.new(params[:emppede])

    respond_to do |format|
      if @emppede.save
        format.html { redirect_to :action => :index, :id => @emppede.ad }
        format.json { render json: @emppede, status: :created, location: @emppede }
      else

        format.html { render action: "new", :id => @emppede.ad } *(....error)*
        format.json { render json: @emppede.errors, status: :unprocessable_entity }
      end
    end
  end

我必须在新方法中传递 id。在这里,如果数据保存正确,那么它会转到索引方法。但如果不是,那么它应该转到新的但带有参数 id。我如何通过渲染 Action 传递参数?我想在这里做,但参数 id 没有传递给新方法。我错误地突出显示了那部分。 如果我这样做

 format.html { redirect_to :action => :new, :id => @emppede.ad }

然后它不给出错误信息...

我必须将用户 ID 传递给新方法,以便我可以通过表单传递它并保存。

<div id="employm" style="display:none">


    <%= f.text_field :ad, :value=> @id%>

            </div>

但是当表单出现错误时,它会呈现为新的,但在这里我必须发送 在 @emppede.ad 中的 ID。 我怎样才能做到这一点? 因为为了进入新方法,应该传递 id

redirect_to :action => :new, :id => @id

最佳答案

您在 Controller 操作中定义的所有实例变量都存在于 View 中。 所以如果你定义 @id = 11在您的 Controller 中,您可以使用 <%= @id %> 在 View 中访问它.

如果您想通过重定向执行此操作,您可以简单地访问 parameters在 View 中(或先在 Controller 中使用它们,然后使用上面的实例方法。

您发布的代码有点神秘,但渲染不会进入 new方法,但只呈现 new.html.erb在当前情况下。因此,如果您在创建操作中声明了 @id 并呈现新的,您就会看到它。

当重定向到 :action 时,您必须将 @id 作为参数传递。

关于ruby-on-rails - 如何在 Rails 中的渲染 Action 中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13449901/

相关文章:

ruby-on-rails - Ruby 语法 : What does the '<' single less than mean in Ruby besides 'less than' ?

ruby-on-rails-3 - 事件管理员 has_many 通过删除关联

ruby-on-rails-3 - 在 cucumber / capybara 中模拟关闭/重新打开浏览器?

ruby-on-rails - rakefile 可以用来做什么?

ruby-on-rails - 为什么主页因微博提交失败而中断 - Michael Hartl Rails 教程

javascript - Rails 应用程序中文本框的 "suggest"功能

python - delayed_job 就像 python 的队列

ruby - IO错误 : closed stream in Ruby SFTP

ruby - `Enumerable#inject` 中的 Symbol 与 Proc

javascript - 与backbone.js 的命名约定(在rails 上)