当我最初调用新函数时,所有变量都正确加载。 params [:code]是路由中定义的URL参数。但是,如果验证在create和new上呈现失败,则不会加载@m变量(当在'new'模板中调用@m的属性时,这会导致nomethoderror)。因此,渲染new后不会获得:code参数。但是,验证失败后可以保留:code参数吗?
class AffiliatesController < ApplicationController
def new
@m = Merchant.find_by_code(params[:code])
@affiliate = Affiliate.new
end
def create
a = Affiliate.new(params[:affiliate])
if a.save
redirect_to 'http://' + params[:ref]
else
render 'new'
end
end
end
答案 0 :(得分:1)
除了使用会话之外,保留params[:code]
的另一种方法是在表单中添加隐藏字段。
<%= form_for @affiliate do |f| %>
<%= hidden_field_tag :code, @m.code %>
然后将创建操作更改为
def create
@affiliate = Affiliate.new(params[:affiliate])
if @affiliate.save
redirect_to 'http://' + params[:ref]
else
@m = Merchant.find_by_code(params[:code])
render :new
end
end
答案 1 :(得分:0)
在致电render
之前,您应该填写视图将使用的所有变量。
因此,在您的情况下,您需要在@m = ...
内render 'new'
之前实例化create
。
如果您需要一个额外的参数来完成此操作(在您的情况下为param[:code]
)我不会建议您配置路由并通过URI传递此信息,这很复杂。
使用会话,它更容易!
例如:
在index
(或您可以使用商家代码的任何地方)添加session[:merchant_code] = the_code
。
在new
更改@m = Merchant.find_by_code(session[:merchant_code])
干杯,