Keep form data when form is loaded a second time - ruby-on-rails

I have a from that does two things.
Gets user text input.
Users can select an image or upload their own.
Problem occurs when user uploads their image.
The file field must submit the information to upload the image. It does all works.
But when the form is shown with the uploaded image, the text the user entered is gone. I understand that the instance variables won't keep the data.
How can I make this work so the text is not lost?
Must I use AJAX?
Thank you in advance.

if you are using form_for,
# your_controller.rb
def new # method where you show the form
#some_model = SomeModel.new(params[:some_model])
end
# new.html.haml - i like haml
- form_for #some_model do
... # all your inputs (they will be pre-set if you submit the form and it stays in new method
if you are using form_tag
# new.html.haml
- form_tag do
= text_field_tag :some_attribute_name, params[:some_attribute_name]
= select_tag :another_attribute_name, options_for_select(['option1', 'option2', 'and so on'], params[:another_attribute_name])
so depends on what you using, choose the respective way ;-) hope this helps =)
HOWEVER
i think the image should be submitted together with the form and saved together, i.e. it shouldn't be a separate process, unless of course you are talking about the form is saved and you are redirecting to an edit page... either way, both methods should work =)

Related

Ruby on Rails, Formtastic Gem image upload

I'm uploading an Image to my Image model using formtastic Gem.
User model has many images
I've created my form using formtastic gem:
= semantic_form_for #user, :remote => true, :html => { :class => 'formtastic' } do |f|
= f.semantic_fields_for :images, #image do |image|
= image.input :file
:label => false,
:as => :file
It is required to upload an image. The form has two more fields Name and description!
After choosing a file to upload it shows the chosen file name.
If I fill out all the required fields and hit submit it works perfectly fine but If I hit submit before filling out all required field then form will ask me to fill out required fields and also asks me choose the file again.
Expected behavior is that form should only ask me to fill out missing required field and it should remember previously chosen file.
Does anyone know why it's doing this?
Any help will be greatly appreciated
When the form is submitted, the file is attached to the request. When the error page returns, the values of the form fields are supplied by the server from the submitted info to rewrite the page. However, the server does not know anything about where the file came from on your system, so cannot re-fetch the file from your system to pre-populate the form.
Anything that would pre-populate the file field would have to have the ability to go into the filesystem on your computer. This is only allowed if you browse to the file yourself.
A couple of solutions are proposed here:
How to persist file upload fields after a rails validation error.
The first couple answers recommend using an attachment-management gem like Paperclip; if you want to avoid using another gem I like the third, which recommends client-side validation of the data through javascript - basically prevent the user from submitting the form to the server with bad info in the first place. Of course you still want to validate on the server side.

Captcha with Multipart Form Rails

I have a multipart form that I need a captcha for at the end. Essentially, a user is allowed to create/update a draft but not submit it for admin review until everything is done. There is a captcha meant for the last submission but the problem is that when I add it to the form, I can't use any of the other submit buttons because the captcha isn't filled out. Is there any way around this?
I'm using simple_captcha and Rails 3.2.
Thanks!
I haven't used simple_captcha before, but seems like you are doing #object.save_with_captcha in every case. You have multiple options to solve this, but one i came up with is:
In the controller, verify if all the fields (mandatory only i guess) are filled, and if they are, then save your object using #object.save_with_captcha, otherwise do the usual #object.save which wont trigger the captcha validation. Something like this:
def create
#object = MyObject.new(params[:my_object])
if #object.has_mandatory_fields_filled?
#object.save_with_captcha
else
#object.save
end
end
In the has_mandatory_fields_filled? method you would check that all the mandatory fields of your form are not empty/nil etc.

Allows user to edit pages that contain variables [duplicate]

This question already has an answer here:
How to render a string as an erb file?
(1 answer)
Closed 9 years ago.
I have some editable pages that are stored as text in my database. These pages will be called in my view like...
#app/views/static_pages/scheduling_text.html.erb
<%= Page.find_by_name("New Registration").content %>
Page.content is of type 'text' (not string). A portion of the text that contains variables would look like...
You have successfully registered for New Student Orientation on #{<%= #registration.orientation.class_date %>} at...
If course when I call this content in the view, I just get the text, not the model values. How can I make these pages access the model values? I also tried adding #{} around the text without success.
This seems to be a duplicate of Rails: storing erb templates in database
Given that, this should do the trick for you, or at least be close enough to get you started:
<%= sanitize ERB.new(Page.find_by_name("New Registration").content).run %>
Additionally, you can remove the sanitize if content is not user-supplied (this is primarily a security concern).
I've done something exactly like this using HAML processing:
= sanitize Haml::Engine.new(article.content).render
For reference, here's the appropriate ERB documentation: http://ruby-doc.org/stdlib-2.0.0/libdoc/erb/rdoc/ERB.html
OK, after much wailing and gnashing of teeth here is the the solution I cam up with. First I am using mustache. This is much safer than storing erb in the templates and prevents malicious injection of sql into your app. I simply added 'mustache' to my gemfile rather than mustache-rails as it seems to be more up to date. I then created a simple Page model with two attributes: :name and :content. I am using the page model to store the raw mustache code.
Here are the relevant files...
In my controller I call...
#app/controllers/registrations_controller.rb
def create
#registration = Registration.new(params[:registration])
respond_to do |format|
if #registration.save
if #registration.orientation != nil
format.html { render "scheduling_text.html.erb" }
Then my view looks like...
#app/views/registrations/scheduling_text.html.erb
<%= Mustache.render(Page.find_by_name("New Registration").content, {:registration => #registration }).html_safe %>
<%= link_to 'Back', orientations_path %>
...
Then in my page model I have something like...
You have successfully registered for New Student Orientation on {{ registration.orientation.class_date }} at {{ registration.orientation.class_time}}. Please arrive 10 minutes prior to your scheduled Orientation. Remember, you must attend this Orientation session before you may register for classes. ...
Using a page model with scaffolding like this works well because it gives you the new, update, and create actions that will allow users to edit content. Note, they can easily mess up your ruby variables, so thats the downside. Just let your users know to not munk with anything that is between {{}}.
Hope this helps someone else out.

submit in rails without formhelpers

I'm new to rails and still learning the ropes via railstutorial, but the book does all changes to the db via form submissions (http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html). But how would I go about submitting (updating the db) without this, lets say I want to add some score which is computed on page ,(for example via a js counter - for simplicity lets just say its a constant 10) and my db consists of a column called score. Then after pressing a submit button how would I go about updating the db?
Thanks
Two trivial ways:
Use a form
Use a URL parameter with a link
The processing (other than GET v. POST) on the Rails side is identical--it's just a parameter.
If you're using JavaScript, there's not necessarily a reason to not use a form, though, since you could just update a form input element and submit normally.
It is quite simple, actually.
The constant 10 is submitted from the view. The submit needs to point to the controller action that will handle this request. So the submit button should build the url using :controller, :action, :id parameters. In a form, this is handled in the form_for declaration. You will deal with in the button_tag declaration.
The routes should be configured so that this message can reach the controller/ action.
The constant 10 is transported in the params hash. If the field is my_counter, then look for params[:my_counter]. If the form had been for a model, say tweets, then it might be in params[:tweet][:my_counter].
In the controller action, possibly update, you will first fetch the record to change with something like #score = Score.find(:params[:id]). This params[:id] is also coming from the view with the submit. Change the counter here, and save.
def update
#score = Score.find(:params[:id])
#score.counter = params[:my_counter]
#score.save
redirect_to :action => :index # or wherever
end
Good luck.

How to keep file field value when validation failed

I have a classic rails 3 form with a file field, everything works fine, upload works and data is saved to database.
When a validation failed, for example, title is missing, then the user is sent back to the form with a render :action => new. Normal. But the problem here, is that the user have to select another time its file.
Any way to avoid that?
Typically you don't want to process files until after validations have run or you're going to repeatedly store files that possibly don't have the associated records. Gems like Paperclip and attachment_fu do this.
If you would rather store the file the first time it's submitted and is valid you can store the file and then do a quick check in your view to see if it's already set for the object you're building a form for, e.g:
<% unless foo.attachment? %>
# file field
<% end %>
Make sense?
You can't. It is security issue.
You can hack it in some browsers, but generally you can't do it
I know the question is old, but now the carrierwave gem has something to retain the file field when the validation fails.
https://github.com/carrierwaveuploader/carrierwave#making-uploads-work-across-form-redisplays
Basically, you will have to add a hidden_field avatar_cache if your model has an uploader mounted on avatar file. You will have to add it to the permit list in the controller (so that Rails wont restrict the field from being submitted to the server)

Resources