Submitting multiple forms in Rails - ruby-on-rails

I have to submit multiple forms, I followed the advice of this post: How to submit multiple, duplicate forms from same page in Rails - preferably with one button
Note I'm still quite new to Rails/programming and some of my ways of doing things might not be ideal.
Here's my view:
= form_tag ([#event, #registration]) do
- x.times do
= render 'multi_form'
= submit_tag "Submit registrations"
The form (note that there are more fields):
- hidden_field_tag :event_id, :value => #event.id
.control-group
= label_tag :title
.controls
= select("registrations[][title]", :registration, Registration::TITLE)
.control-group
= label_tag :first_name
.controls
= text_field_tag "registrations[][first_name]"
.control-group
= label_tag :last_name
.controls
= text_field_tag "registrations[][last_name]"
.control-group
= label_tag :email
.controls
= text_field_tag "registrations[][email]"
The controller:
def create
array_number = 0
x.times do
#registration = Registration.new(params[:registrations][array_number])
#registration.save
UserMailer.registration_user_notify(#event, #registration).deliver
array_number = array_number + 1
end
respond_to do |format|
format.html {redirect_to thank_you_event_registrations_path(#event)}
end
end
When submitting it seems, to an extent, to be doing the right thing, for one it fires off an email to x unique email addresses, which makes me think that #registration contains the correct details in each loop - it's not saving to the database however. I can see that all the params are there in the log file, except that :title seems to be doing something bad (see below: but I'll focus on that later), the main thing I want it to do now is run though each array and save it as a new entry.
The log:
Parameters: {"utf8"=>"â", "authenticity_token"=>"BQXm5fngW27z/3Wxy9qEzu6D8/g9YQIfBL+mFKVplgE=", "event_id"=>"7", "registrations"=>[{"title"=>{"registration"=>"Mrs"}, "first_name"=>"Person", "last_name"=>"One", "email"=>"charl#privatelabel.co.za"...
I'm hoping the info I provided is enough, any advice will be appreciated.
Thanks!
EDIT:
#iblue
It did the trick! It was a validation error and it's saving everything into different rows. Thank you very much!
One more thing if I may, any idea how the :title form part should be formatted in order to return paramater:
"title"=>"Mrs",
as opposed to:
"registrations"=>[{"title"=>{"registration"=>"Mrs"},
Thanks again!

You are not checking if #registration.save actually saves the record. It can return true or false. I guess it just silently fails.
If you use #registration.save!, it wile raise an exception when anything goes wrong. I guess there is some kind of validation error there.

Related

Edit and destroy image paperclip rails

I have problem with paperclip gem. I'm using Rails 4. I would like to make possiblity for user, to edit image attachment. For now when I'm editing Speaker, I can only upload new image, no edit existing one.
= simple_form_for(#speaker) do |f|
= f.error_notification
.form-inputs
= f.input :first_name
= f.input :nickname
= f.input :last_name
= f.input :description
- if #speaker.image.exists?
= image_tag #speaker.image.url(:medium)
= f.input :delete_image, as: :fake
= #speaker.image = nil
= #speaker.save
= f.input :image
.form-actions
= f.button :submit
However, I can't create checkbox input with :delete_image, so for now, with every refresh site it destroys image (because of #speaker.save).
Could give me some advice, how to fix it ? Solutions from Rails 3 cant help me.
In your controller
def remove_picture
speaker = Speaker.where(id: params[:id]).first
speaker.image.destroy
redirect_to request.referer
end
in your view create following link -
- if #speaker.image.exists?
= link_to "Remove Image", remove_image_path(#speaker), method: :delete
in your routes.rb define routes for same
delete'/controller/remove_image/:id' => 'controller#remove_image', as: :remove_image
Try above code.
Do you mean you want the user to be able to edit the image like they would in Photoshop, or similar (perhaps more simple) image editing apps? If so then your best option is to use a javascript plugin, eg one of these jQuery plugins:
http://www.sitepoint.com/image-manipulation/
http://www.jqueryrain.com/2014/11/picedit-jquery-front-end-image-editor-plugin/
These were got just by googling "jquery image editor plugin".
See also this related question: Javascript image editing plugin
You will need to choose which one is the best fit for you based on the types of editing options you want to give your user.

Rails Parse Form Input

I'm using a form to transfer some data from one part of a controller to another (new to create), but I'm having some trouble with it. When I try to get the data after submitting the form, it just gives me a nil value.
Here's the form code:
<%= f.hidden_field :owner_id, :value => #tool.user_id %>
<%= f.hidden_field :tool_id, :value => #tool.id %>
<%= f.hidden_field :borrower_id, :value => current_user.id %>
And this is the create action in the controller:
def create
render text: params[:rental_agreement].inspect
#rental_agreement = RentalAgreement.create
#rental_agreement.owner_id = params[:owner_id]
# render text: #rental_agreement.inspect
end
When I hit the "Submit" button on the form, I see this:
{"owner_id"=>"3", "tool_id"=>"1", "borrower_id"=>"4"}
That's fine, but when I change which inspection renders (comment out the top line, uncomment the bottom), all it displays is:
#
And if I look in the Rails console at this object, all of the fields in it are nil (except the id and created_at fields).
I'm just trying to figure out how to assign the variables from the form (owner_id, tool_id, and borrower_id) to the rental_agreement variable. Any help is much appreciated!
Your create method seems wrong. Try this.
def create
#rental_agreement = RentalAgreement.new(params[:rental_agreement])
#rental_agreement.save
end

Render custom page/s after validation fails

I'm using the High Voltage gem (https://github.com/thoughtbot/high_voltage/) for a site with masses of static pages. The site has three unique forms all which are handled by the 'forms' controller/model.
Now all is working well when fields which requires validation are populated, but when validation fails it jumps from the 'pages' controller (High Voltage) back to the 'forms' controller and renders /form/new, instead of, for instance, /pages/quotes - which is understandable as it's default behaviour.
I'm also checking for validation in the form:
= form_for #form, :validate => true do |f|
- if #form.errors[:name].present?
.control-group.error
= f.label "Your Name"
= f.text_field :name
- else
= f.label "Your Name"
= f.text_field :name
Any idea how I can re-render the current page (which renders the specific form) after validation fails instead of directing to /forms/new
Any advice appreciated, thanks!

Rails form formatting

I've just had Submitting multiple forms in Rails answered which led to another problem. In my form I have the following (there's quite a bit more):
= hidden_field_tag :event_id, :value => #event.id
.control-group
= label_tag :title
.controls
= select(:registration, "registrations[][title]", Registration::TITLE)
and the last line returns:
"registrations"=>[{"title"=>{"registration"=>"Mr"},
as opposed to the expected:
"title"=>"Mr"
I've tried:
= select(:registration, "registrations[][title]", Registration::TITLE)
which returns:
undefined method `registrations[][title]' for #
and also tried:
= select("registrations[][title]", Registration::TITLE)
which returns:
wrong number of arguments (2 for 3)
Look at the parameters below, event(_id) is only there once then the :title oddness starts, any idea what the problem may be?
{"utf8"=>"✓",
"authenticity_token"=>"BQXm5fngW27z/3Wxy9qEzu6D8/g9YQIfBL+mFKVplgE=",
"event_id"=>"7",
"registrations"=>[{"title"=>{"registration"=>"Mr"},
"first_name"=>"Name1",
"last_name"=>"Surname1",
"company_name"=>"Company1",
"designation"=>"Designation1",
"landline"=>"Landline1",
"cell"=>"Cell1",
"email"=>"address1#example.com",
"member"=>{"registration"=>"No"},
"dietary"=>{"registration"=>"None"},
"specify"=>"None"},
{"first_name"=>"Name2",
"last_name"=>"Surname2",
"company_name"=>"Company2",
"designation"=>"Designation2",
"landline"=>"Landline2",
"cell"=>"Cell2",
"email"=>"address2#example.com",
"member"=>{"registration"=>"No"},
"dietary"=>{"registration"=>"None"},
"specify"=>"None",
"title"=>{"registration"=>"Mr"}},
{"first_name"=>"Name3",
"last_name"=>"Surname3",
"company_name"=>"Company3",
"designation"=>"Designation3",
"landline"=>"Landline3",
"cell"=>"Cell3",
"email"=>"address3#example.com",
"member"=>{"registration"=>"No"},
"dietary"=>{"registration"=>"None"},
"specify"=>"None"}],
"commit"=>"Submit registrations"}
Please not that :dietary and :member are formated in the same way as :title. Thanks in advance for your assistance!
EDIT
So submitting to the hash via a text_field_tag is a simple is:
= text_field_tag "registrations[][first_name]"
But the problem comes in with my hidden_field_tag and select_tag.
It's adding bad values, for example:
"title"=>{"registrations"=>"Mr"}
and basically it seems I need to find a better way to add those values into the hash. I'll continue trying to find a solution and will post it here unless someone beats me to it.
Unless i'm reading it wrong, your first two select calls are the same. Have you tried = select(:registrations, "title", Registration::TITLE)? If you look at the documentation of the method in api.rubyonrails.org, it will state that the first value is the object, second is the property. That would be registrations => { :title => "Value" }, in the parameters. If you just want :title => "Value", then you need the select_tag method.

Retain Search Form Data Ruby On Rails

Trying to build a search on my homepage with simple_form (Pretty much same as formtastic). The search works fine and im getting my results but after submission I want to retain the vales with what the user submitted.
I am using a namespace for my form so how can I retain the data for the form. Here is some code which may help.
Controller
def index
#results = Property.search(params[:search])
end
View
%h1 Search Form
= simple_form_for(:search) do |f|
= f.input :location, :as => :select, :collection => Location.all.asc(:name)
= f.input :type, :collection => PropertyType.all.asc(:name)
= f.input :bedrooms, :collection => 1..10,
%p.box
= f.button :submit
-if #results
%h1 Search Results
.results
- #results.each do |property|
.result
%h1= property.title
Within the Index controller I have tried all sorts of things ie
#search = params[:search]
But each time I try something the search breaks.
What am I doing wrong ?
Hope you can advise
One approach is to do as Xavier Holt suggested, and pass in values to each input. The simpleform doco suggests:
= f.input :remember_me, :input_html => { :value => '1' }
The other approach is to have simpleform do it for you. SimpleForm will automatically populate the fields with values if you give it something like an activerecord object.
In this case, that means creating a model object:
class PropertySearchCriteria
attr_accessor :location, :type, :bedrooms
def initialize(options)
self.location = options[:location]
self.type = options[:bedrooms]
self.bedrooms = options[:bedrooms]
end
end
Then, change your controller:
def index
#property_search_criteria = PropertySearchCriteria.new(params[:search])
#results = Property.search(#property_search_criteria)
end
(you'll have to change the Property.search method as well)
Then, change your simple_form_for:
= simple_form_for(:search, #property_search_criteria) do |f|
And if you do all that, and get the stars to align just right, then simpleform will pre-populate the form fields all by itself. You may have to add some stuff to PropertySearchCriteria to get simpleform to be properly happy.
This is a lot of stuffing around just to get the values showing up, but it'll keep you sane if you need to add validations.
I'm doing something similar in the app I'm working on (I'm not using formtastic, but this should be at least very close to something that works for you). I got around it by making sure #search was a hash in the controller:
#search = params[:search] || {}
And then using #search[:key] as the :value option in all my search inputs (There's a chance you'll need to set #search.default = '' to get this working):
<%= text_field_tag :name, :value => #search[:name] %>
And that's all it took. As my app is getting more complicated and AJAXy, I've been thinking of moving the search parameters into the session information, which you might want to do now to stay ahead, but if you're just looking for a simple solution, this worked great for me.
Hope this helps!
you can try storing your parameters in session like so:
def index
#results = Property.search(params[:search])
store_search
end
def store_search
session[:search] = params[:search]
end
just be sure when you are done with the parameters that you clean them up
...
clear_search if session[:search]
def clear_search
session[:search] = nil
end

Resources