Get an array from a Rails form - ruby-on-rails

I need to design a form for a account resource. In that form, i need to collect some set of ids as an array in the params hash in attribute called relationships.
So the final params[account] hash from the POST request should be like:
{:name => 'somename', :relationships => ["123", "23", "23445"]}
How shall I design the form_for fields? I tried this, but didn't work:
<%= form_for #account do |f| %>
<%= f.text_field :name %>
<% #eligible_parents.each do |p| %>
<%= f.check_box "relationships", nil, :value => p.id %>
<b><%= p.name %></b><br/>
</span>
<% end %>
<%= f.submit "Submit" %>
<% end %>
Number of elements in #eligible_parents varies every time.
relationships is neither an association nor an attribute in account model.
I have to use virtual attributes but I need to fill in an array from a form.
Please help. How can I do this?

You still need a fields_for in your view, just use :relationships as the record_name then provide an object.
<%= form_for #account do |f| %>
<%= f.text_field :name %>
<% fields_for :relationships, #eligible_parents do |p| %>
<%= p.check_box "relationships", nil, :value => p.object.id %>
<b><%= p.object.name %></b><br/>
<% end %>
<%= f.submit "Submit" %>
<% end %>
Documentation here: ActionView::Helpers::FormHelper

I found this to be the cleanest way...
If you are working with straight data and want to send back an array without using any of these #objects:
<%= form_for :team do |t| %>
<%= t.fields_for 'people[]', [] do |p| %>
First Name: <%= p.text_field :first_name %>
Last Name: <%= p.text_field :last_name %>
<% end %>
<% end %>
your params data should return like this:
"team" => {
"people" => [
{"first_name" => "Michael", "last_name" => "Jordan"},
{"first_name" => "Steve", "last_name" => "Jobs"},
{"first_name" => "Barack", "last_name" => "Obama"}
]
}

If you want to send array of values just use [] in name attributes.In your case just use
<%= f.check_box "relationships", {}, :value => p.id, :name => "relationships[]" %>

In a complex form, with nested attributes, you can make use of the f.object_name helper. But beware of the syntax when doing interpolation. This is correct:
"#{f.object_name}[relationships][]"
This is NOT correct:
"#{f.object_name}[relationships[]]"
It always trips me up.

I'm working in something similar. My issue was how to pass the input name to a partial to resolve it as a hash using the rails form_for helper.
So, my solutions was something like this:
= render 'my_partial', form: form, name: "item_ids[item.id]"
So, this gonna render an html like this:
<input class="form-control" name="products[items_ids[1]]" id="products_items_ids[1]">
The number 1 is the item.id, this is how HTML understand that you gonna pass an array or hash, all depends your config.
So, the params gonna look like this:
"items_ids"=>{"1"=>"1"}
This is working for me with an form_object + virtus

Related

Rails check_box_tag within form_for

Is it possible to pass the value of checked check_box_tags within a form_for in Rails inside a hash?
Here is a very generic, basic version of the form:
<%= form_for(:object, :url => { :action => 'create', :id => params[:id]}) do |f| %>
<p>Field_a: <%= f.text_field(:field_a) %></p>
<p>Field_b: <%= f.text_field(:field_b) %></p>
<p>Field_c: <%= f.text_field(:field_c) %></p>
<p>Check boxes:</p>
<% check_box_choices_object_array.each do |s| %>
<%= check_box_tag(s.name, 1, false) %>
<%= .name %><br />
<% end %>
<%= submit_tag("Create") %>
<% end %>
Outputs roughly:
Field_a ___________________
Field_b ___________________
Field_c ___________________
Check boxes:
[] box_a
[] box_b
[] box_c
[] box_d
[] box_e
[] box_f
[] box_g
My problem is that since the available check boxes aren't actual fields in the object's table in the database (i.e. I'm not using check_box(:field) in the form), each checked check box gets passed as an individual parameter (i.e. "box_a" => "1", "box_b" => "1", "box_e" => "1"). I would like them to be passed as such:
:checked_boxes => {"box_a" => "1", "box_b" => "1", "box_e" => "1"}
This way, I can access them easily with params[:checked_boxes].
How do I do this, or, better yet, is there a better solution (I'm new to rails)?
I think you'd get the results you want if you wrap the checkboxes iterator in a fields_for :checked_boxes tag - or at least get you close to the results you want.
<%= form_for(:object, :url => { :action => 'create', :id => params[:id]}) do |f| %>
<p>Field_a: <%= f.text_field(:field_a) %></p>
<p>Field_b: <%= f.text_field(:field_b) %></p>
<p>Field_c: <%= f.text_field(:field_c) %></p>
<p>Check boxes:</p>
<%= f.fields_for :checked_boxes do |cb| %>
<% check_box_choices_object_array.each do |s| %>
<%= cb.check_box(s.name, 1, false) %>
<%= .name %><br />
<% end %>
<% end %>
<%= submit_tag("Create") %>
<% end %>
you can deal with no database attributes and models using attr_accessor
class Thing < ActiveRecord::Base
attr_accessible :name
attr_accessor :box_a, :box_b, :box_c
end
This way you can call these attributes in your form.

How does Rails group arrays of hashes during form submission?

According to the Rails Guides and this Railscasts episode, when there's a one-to-many association between two objects (e.g. Project and Task), we can submit multiple instances of Task together with the Project during form submission similar to this:
<% form_for :project, :url => projects_path do |f| %>
<p>
Name: <%= f.text_field :name %>
</p>
<% for task in #project.tasks %>
<% fields_for "project[task_attributes][]", task do |task_form| %>
<p>
Task Name: <%= task_form.text_field :name %>
Task Duration: <%= task_form.text_field :duration %>
</p>
<% end %>
<% end %>
<p><%= submit_tag "Create Project" %></p>
<% end %>
This will result multiple copies of an HTML block like this in the form, one for each task:
<p>
Task Name: <input name="project[task_attributes][name]">
Task Duration: <input name="project[task_attributes][duration]">
</p>
My question is, how does Rails understand which
(project[task_attributes][name], project[task_attributes][duration])
belong together, and packing them into a hash element of the resulting array in params? Is it guaranteed that the browsers must send the form parameters in the same order in which they appear in the source?
Yes, ordering is retained as-is, as #k-everest self-answered as a comment to original question.
Those asking for HTML, see the guide on how the attribute's name is parsed.
Example of typically bad ordering:
cart[items][][id]=5
cart[items][][id]=6
cart[items][][name]=i1
cart[items][][name]=i2
And that gets parsed by Rails into this:
{ "cart"=> {"items"=> [
{"id"=>"5"},
{"id"=>"6", "name"=>"i1"},
{"name"=>"i2"}
]}}
Example source: https://spin.atomicobject.com/2012/07/11/get-and-post-parameter-parsing-in-rails-2/
The feature was added in Rails' initial commit, with method name build_deep_hash. For more history, skip the flaming/semantics war and go for the last post from the end here: https://www.ruby-forum.com/topic/215584
if you are working with straight data and want to send back an array without using any of these #objects
<%= form_for :team do |t| %>
<%= t.fields_for 'people[]', [] do |p| %>
First Name: <%= p.text_field :first_name %>
Last Name: <%= p.text_field :last_name %>
<% end %>
<% end %>
your params data should return like this
"team" => {
"people" => [
{"first_name" => "Michael", "last_name" => "Jordan"},
{"first_name" => "Steve", "last_name" => "Jobs"},
{"first_name" => "Barack", "last_name" => "Obama"}
]
}

Ruby/Rails - Insert Parameters Into Query String Located In the Controller

I have a link_to in my view which is going to a URL( query string) that is created dynamically in the controller.
<%= link_to "Search Venue", #venue_search, :target => :blank %>
and in the controller I'm pulling some attributes from a model and using those values in a query to hit Yahoo's API and
#event = Event.find(params[:id])
search_values = {
:api_key => 'xxxxxxxxx',
:search_text => #event.venue_name,
:location => #event.venue_zipcode,
:radius => 100
}
#venue_search = "http://yahooapis.com/rest/?method=venue.search&" + search_values.to_query
And everything is working perfect so far.
I would like to manually enter a few more parameters into the query and I'm just wondering what would be the best direction to go.
Is there a way to create a form which some text fields that I can use to insert parameters manually into the query string and to use the submit button to call the url as a link_to?
I was thinking something like
<% form_for #venue_search(:city, :state) do |f| %>
<%= f.text_field :city %>
<%= f.text_field :state %>
<% end %>
And some how add those two new parameters to the query and then execute the query
Is that possible?
If i properly understand your question, you can use for sending 'GET' request - in such case parameters will be placed in query:
<% form_for #venue_search, :method => :get do |f| %>
<%= f.text_field :city %>
<%= f.text_field :state %>
<% end %>
Hope its help you.

Nested Forms - fields_for() and symbols

I've been struggling with this for the last several hours:
I have a nested form (shown below) and it's working, but for the life of me, I cannot figure how to access the :student_id in the _form_outcome_ratings.html.erb. It displays the appropriate student_id in the hidden field that's created, but I have no idea how to access that number to display the student's name next to the rating field. When I try to reference :student_id or :student_id.to_s it returns "student_id" instead of the number. I think I'm missing or misunderstanding something very basic, but I can't figure out what!
Thank you for taking the time to look at this, and let me know if there's anything I need to clarify or add.
/app/views/learning_outcomes/_form_rate.html.erb
<% form_for(#learning_outcome) do |f| %>
<% f.fields_for :outcome_ratings do |g| %>
<%= render :partial => 'form_outcome_ratings', :locals => {:f => g} %>
<% end %>
<%= f.submit %>
<% end %>
/app/views/learning_outcomes/_form_outcome_ratings.html.erb
<%= f.hidden_field :student_id %>
<%= f.label :rating %><%= f.text_field :rating %>
/app/controllers/learning_outcomes_controller.rb
def rate
#learning_outcome = LearningOutcome.find(params[:id], :include => {:section => {:students => {:outcome_ratings => [:learning_outcome, :student]}}})
#learning_outcome.section.students.each do |student|
#learning_outcome.outcome_ratings.build(:student_id => student.id) if student.outcome_ratings.where(:learning_outcome_id => #learning_outcome.id).blank?
end
end
Not sure I understod what you want, but...
You can access all variables of a model within a form builder if you do as follows:
f.object.your_variable
example:
f.object.id

Multiple forms for the same model in a single page

On the front page of my rap lyrics explanation site, there's a place where users can try explaining a challenging line:
alt text http://dl.dropbox.com/u/2792776/screenshots/2010-02-06_1620.png
Here's the partial I use to generate this:
<div class="stand_alone annotation" data-id="<%= annotation.id %>">
<%= song_link(annotation.song, :class => :title) %>
<span class="needs_exegesis"><%= annotation.referent.strip.gsub(/\n/, "\n <br />") %></span>
<% form_for Feedback.new(:annotation_id => annotation.id, :created_by_id => current_user.try(:id), :email_address => current_user.try(:email)), :url => feedback_index_path, :live_validations => true do |f| %>
<%= f.hidden_field :annotation_id %>
<%= f.hidden_field :created_by_id %>
<p style="margin-top: 1em">
<%= f.text_area :body, :rows => 4, :style => 'width:96%', :example_text => "Enter your explanation" %>
</p>
<p>
<% if current_user %>
<%= f.hidden_field :email_address %>
<% else %>
<%= f.text_field :email_address, :example_text => "Your email address" %>
<% end %>
<%= f.submit "Submit", :class => :button, :style => 'margin-left: .1em;' %>
</p>
<% end %>
</div>
However, putting more than one of these on a single page is problematic because Rails automatically gives each form an ID of new_feedback, and each field an ID like feedback_body (leading to name collisions)
Obviously I could add something like :id => '' to the form and all its fields, but this seems a tad repetitive. What's the best way to do this?
If you don't want to change your input names or your model structure, you can use the id option to make your form ID unique and the namespace option to make your input IDs unique:
<%= form_for Feedback.new(...),
id: "annotation_#{annotation.id}_feedback"
namespace: "annotation_#{annotation.id}" do |f| %>
That way our form ID is unique, i.e. annotation_2_feedback and this will also add a prefix, e.g. annotation_2_, to every input created through f.
Did you consider nested_attributes for rails models? Instead of having multiple new feedback forms where each is tied to an annotation, you could have multiple edit annotation forms where each annotation includes fields for a new feedback. The id's of the generated forms would include the annotations id such as edit_annotation_16.
The annotation model would have a relationship to its feedbacks and will also accept nested attributes for them.
class Annotation < ActiveRecord::Base
has_many :feedbacks
accepts_nested_attributes_for :feedbacks
end
class Feedback < ActiveRecord::Base
belongs_to :annotation
end
You could then add as many forms as you want, one for each annotation. For example, this is what I tried:
<% form_for #a do |form| %>
Lyrics: <br />
<%= form.text_field :lyrics %><br />
<% form.fields_for :feedbacks do |feedback| %>
Feedback: <br/>
<%= feedback.text_field :response %><br />
<% end %>
<%= form.submit "Submit" %>
<% end %>
<% form_for #b do |form| %>
Lyrics: <br />
<%= form.text_field :lyrics %><br />
<% form.fields_for :feedbacks do |feedback| %>
Feedback: <br/>
<%= feedback.text_field :response %><br />
<% end %>
<%= form.submit "Submit" %>
<% end %>
And the quick and dirty controller for the above edit view:
class AnnotationsController < ApplicationController
def edit
#a = Annotation.find(1)
#a.feedbacks.build
#b = Annotation.find(2)
#b.feedbacks.build
end
def update
#annotation = Annotation.find(params[:id])
#annotation.update_attributes(params[:annotation])
#annotation.save!
render :index
end
end
I had this same issue on a site I'm currently working on and went with the solution you mention at the bottom. It's not repetitive if you generate the ID programmatically and put the whole form in a partial. For example, on my site, I have multiple "entries" per page, each of which has two voting forms, one to vote up and one to vote down. The record ID for each entry is appended to the DOM ID of its vote forms to make it unique, like so (just shows the vote up button, the vote down button is similar):
<% form_for [entry, Vote.new], :html => { :id => 'new_up_vote_' + entry.id.to_s } do |f| -%>
<%= f.hidden_field :up_vote, :value => 1, :id => 'vote_up_vote_' + entry.id.to_s %>
<%= image_submit_tag('/images/icon_vote_up.png', :id => 'vote_up_vote_submit' + entry.id.to_s, :class => 'vote-button vote-up-button') %>
<% end -%>
I also had the same issue but wanted a more extensible solution than adding the ID to each field. Since we're already using the form_for ... |f| notation the trick is to change the name of the model and you get a new HTML ID prefix.
Using a variant of this method: http://www.dzone.com/snippets/create-classes-runtime (I removed the &block stuff)
I create a new model that is an exact copy of the model I want a second form for on the same page. Then use that new model to render the new form.
If the first form is using
#address = Address.new
then
create_class('AddressNew', Address)
#address_new = AddressNew.new
Your ID prefix will be 'address_new_' instead of 'address_' for the second form of the same model. When you read the form params you can create an Address model to put the values into.
For those stumbling here, looking for the solution for Rails 3.2 app, look at this question instead:
Rails: Using form_for multiple times (DOM ids)

Resources