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/