Reputation: 1531
When I initially call the new function all variables load up correctly. The params[:code] is a URL param defined in routes. However, when validation fails on create and new is rendered, the @m variable is not loaded (this causes a nomethoderror when an attribute of @m is called in the 'new' template). So, the :code parameter is not obtained after rendering new. However can the :code parameter be preserved after validation fails?
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
Upvotes: 1
Views: 1542
Reputation: 29599
Another way to preserve params[:code]
, aside from using the session, is to add a hidden field in the form.
<%= form_for @affiliate do |f| %>
<%= hidden_field_tag :code, @m.code %>
Then change the create action to
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
Upvotes: 1
Reputation: 167
before you call render
you should fill in all the variables that will be used by the view.
So in your case you need to instantiate @m = ...
before you render 'new'
from within the create
as well.
If you need an extra parameter to accomplish this (the param[:code]
in your case) I would not recomment you to configure routes and pass this information over the URI, it's complicated.
Use the session instead, it's a lot easier!
For example:
in index
(or wherever you have the merchant code available) add session[:merchant_code] = the_code
.
in new
change @m = Merchant.find_by_code(session[:merchant_code])
Cheers,
Upvotes: 0