Rails doesn't populate dynamic generated fields on error on posting
In our rails application we have a page where upon submit we save data in db. On this page, we have some fields which are dynamically generated and I see that in case of a validation error when page reloads it doesn't populate these fields with the values present upon posting.
In controller we have the following method defined for populating it:
def build_my_registrati开发者_如何学Goon_type_memberships
@memberships = []
ListCache.my_registration_types.each do |my_registration_type|
@memberships << MyRegistrationTypeMembership.find_or_initialize_by_my_id_and_my_registration_type_id( @my.id, my_registration_type.id )
end end
In above method when my registration is opened in edit/view mode, it shows the values using this @membership method. But on posting in case of error it doesn't reload this with correct information. So my question is how could I repopulate @membership in case of an error on posting?
Thanks for help.
As, I understand you want some values available to your new method or the page that is rendered after if the create fails.
I assume you must have have the respond_to block in your create method. And you're doing this:
def create
...
respond_to do |format|
if @patient.save
format.html { redirect_to @object, :notice => "Object was successfully saved." }
format.xml { render :xml => @object, :status => :created, :location => @object }
else
format.html { render :action => :new }
format.xml { render :xml => @patient.errors, :status => :unprocessable_entity }
end
end
end
As you can notice, in the else part the new action is just rendered. Using some template the view is just delivered. Now, you just have to do whatever you're doing in the new action to make those values available, in the else part.
def create
...
respond_to do |format|
if @patient.save
format.html { redirect_to @object, :notice => "Object was successfully saved." }
format.xml { render :xml => @object, :status => :created, :location => @object }
else
format.html {
@memberships = []
ListCache.my_registration_types.each do |my_registration_type|
@memberships << MyRegistrationTypeMembership.find_or_initialize_by_my_id_and_my_registration_type_id( @my.id, my_registration_type.id )
end
render :action => :new
}
format.xml { render :xml => @patient.errors, :status => :unprocessable_entity }
end
end
end
And, the values you wanted will be available in the rendered form.
Better, you move to that code to a before filter or something, which makes those values available to those two methods (new and create).
精彩评论