ruby on rails - After validation fails and a form redirects back to itself, why are instance variables empty? -
in rails 3.2 app, when form fails save (validation fails) , redirects form error:
undefined method `map' nil:nilclass
this form not display errors when navigating directly new or edit paths.
the error coming select field custom options_from_collection_for_select
method.
<%= f.select(:user_ids, options_from_collection_for_select_with_attributes(@users, :id, :name, 'data-attributes', :attributes ), {include_blank:true}, {multiple:true}) %>
if replace instance variable @users
user.all
don't error after redirect.
i guess @users
empty after redirect, hence error. why? @users
defined in new , edit controllers.
my controller is:
def create --bunch of stuff if @model.save --bunch of stuff respond_to |format| format.html { render :text => model_url(@model) } format.html { redirect_to(@model, :notice => 'success!.') } format.xml { render :xml => @model, :status => :created, :location => @model } end else respond_to |format| format.html { render :action => "new" } format.xml { render :xml => @model.errors, :status => :unprocessable_entity } end end end
it's because don't execute "new" action if fails. here's typical controller structure
class potscontroller < applicationcontroller def new @pot = pot.new @users = user.all end def create @pot = pot.new(params[:pot]) if @pot.create redirect_to @pot, notice: "created" else #****you here**** render :new end end end
in above, if pot.create
fails, renders new template. should instance variables in case too
def create @pot = pot.new(params[:pot]) if @pot.create redirect_to @pot, notice: "created" else @users = user.all #this important line render :new end end
Comments
Post a Comment