Capturing errors for individual forms - ruby-on-rails

I am trying to capture validation errors for individual forms as I have many on one page.
I am giving each form its own unique id by using object_id
<% object = #document || Document.new %>
<%= form_for object, :html => { id: object.object_id.to_s } do |f| %>
But if i do this to capture errors the same error message will appear on all my forms
<% if object.errors.any? %>
# errors
<% end %>
I have tried
<% if object.object_id.errors.any? %>
But i get
undefined method `errors' for 59187740:Fixnum
Is there a way around this please
Thanks
Edit
i have just noticed that the form id changes when validation fails as the page reloads, so that explains why the object cannot be found.
How can i keep the form id the same?

If really depends on what you want to do with the errors:
You want to show them for each form:
<%= form_for some_object, do |f1| %>
<%= f1.error_messages %>
<%= # f1 magic %>
<%= form_for other_object, do |f2| %>
<%= f2.error_messages %>
<%= # f2 magic %>
You want to access them for each object:
just call object.errors: some_object.errors
What isn't working for you:
Calling object_id on an object access its id which is a number (FixNum). You are trying to call a method/access an attribute on a FixNum which does not exist.
You just want some persistent ID for your form
I assume that your object is coming from a database and already has an ID. So why don't you just use object.id? Every time Rails create an ActiveRecord object for you from the DB, that object gets a new object_id. So it is only logical that the ID doesn't stay the same since you have a new object in memory. Read more about it here:
https://stackoverflow.com/a/3430487/2295964

Related

Rails, fields_for, merging records

I'm using fields_for(), not for a nested form, but to display a form containing joined items. I need to display data from #seasons, that help me filling drinks...
<% #seasons do |season| %>
<%= fields_for "drinks[]", season.drink do |f| %>
...
<%= f.select :optimized_region_id ... %>
...
<% end %>
<% end %>
It works well.
However, even if #seasons are never the same, some season.drink could be the sames items as they are "parent" relations. (same season.drink.id)
It's not a problem for me.
My issue is that the form sends this:
drinks"=>{
"e80e15c1-a5d4-4df4-80c6-2efa96e39793"=>{"optimized_status"=>"1", "optimized_nickname"=>"Alex"},
"b7501fe0-3a78-412e-88d5-e7643d761a98"=>{"optimized_status"=>"1", "optimized_nickname"=>"Paul"}
...
}
and should send this:
drinks"=>{
"e80e15c1-a5d4-4df4-80c6-2efa96e39793"=>{"optimized_status"=>"1", "optimized_nickname"=>"Alex"},
"e80e15c1-a5d4-4df4-80c6-2efa96e39793"=>{"optimized_status"=>"0", "optimized_nickname"=>"Alex"},
"b7501fe0-3a78-412e-88d5-e7643d761a98"=>{"optimized_status"=>"1", "optimized_nickname"=>"Paul"}
...
}
It seems that Rails is merging drinks that have the same id when the form is sent. Is there a possibility to avoid this and send all drinks even if they have the same drink.id ?
I found a workaround setting the season_id in the [] :
<%= fields_for "drinks[#{season.id}]", record.drink do |f| %>
Now, all my drinks are sent from the form, evene the ones with same id.

Declare Variable from .each Iteration in Controller

I am attempting to create a method for a self referential relationship that requires two variables to be declared in the controller method...
1) The current record the user is viewing [record = Record.find(params[:parent_id])]
2) The record being selected from a record.each iteration on the primary record's "Show" page as shown below...
<% Record.find_each do |record| %>
<div>
<%= record.name %>
</div>
<%= form_for(#record.active_relationships.build) do |f| %>
<div>
<%= hidden_field_tag :parent_id, record.id %>
</div>
<%= f.submit "Follow" %>
<% end %>
<% end %>
How can this record be declared as a variable in the controller similar to that done with the primary record (1)?
Below is the the method I have in the controller so far...
def create
record = Record.find(params[:parent_id])
record.follow(record)
redirect_to record
end
As you will notice there are two instances of record in the second line. the problem I am having is arising in that I am unsure as how to define the second instance of record to reflect objective 2.
By adding the following lines to the form and controller respectively I was able to define the currently viewed record as the child in the self referential relationship thus allowing the relationship to be created between two records...
Form
<%= hidden_field_tag :child_id, #ingref.id %>
Controller
current_ingref = Ingref.find(params[:child_id])

getting text field value from view page into controllers page

I have a text field "tf_Designation" in a view page, see below:
<% form_for(:search) do |f| %>
<table>
<tr>
<td align="center">
<%= f.text_field :tf_Designation,placeholder: "Designation" %>
</td>
</tr>
</table>
<% end %>
I want to get text field value into a controllers page and I am doing like below:
def search
#blah=params[:search][:tf_Designation]
if !params[:search][:tf_Designation].blank?
#Designation = params[:search][:tf_Designation]
render '/index'
end
end
And I do not have search model. But it gave me error at this line #blah=params[:search][:tf_Designation]. The error is below:
undefined method `[]' for nil:NilClass
Kindly suggest me where I make mistake, waiting for your reply. Thanks
It's most likely an issue with how Rails processes form_for - we've only ever used instance variables with it (which can be populated by a resource):
form_for
Form helpers are designed to make working with resources much easier
compared to using vanilla HTML.
Typically, a form designed to create or update a resource reflects the
identity of the resource in several ways
(i) the url that the form is
sent to (the form element's action attribute) should result in a
request being routed to the appropriate controller action (with the
appropriate :id parameter in the case of an existing resource)
(ii)
input fields should be named in such a way that in the controller
their values appear in the appropriate places within the params hash,
(iii) for an existing record, when the form is initially
displayed, input fields corresponding to attributes of the resource
should show the current values of those attributes.
form_tag
I would highly recommend switching to form_tag, as this deals with perishable data:
#app/views/elements/_search.html.erb
<%= form_tag "/search" do %>
<%= text_field_tag :tf_Designation, nil, placeholder: "Designation" %>
<%= submit_tag "Search" %>
<% end %>
#app/controllers/your_controller.rb
def search
#designation = params[:tf_Designation]
unless #designation.blank?
render '/index'
end
end

Rails - Error rendering 'category' model values in the index view

Unable to render category name in the index view, when passing
<%= post.category.name %>
to the
<% #posts.each do |post| %>
Error:
undefined method `name' for nil:NilClass
However, when passing
<%= post.category %>
I get
#<Category:0x007ff5c2c20b68>
Within individual Show actions
<%= #post.category.id %>
works perfectly. What can be the problem?
Thanks
I think that for atleast 1 post, the category is nil
You can avoid the error by making this change
<%= post.category.name if post.category %>
or
<%= post.category.try :name %>
Look at the SELECT commands that are being invoked in each case, you can see it in your terminal where you run rails s
I suspect that for some reason, in the index controller, the categories information is not being retrieved together with the posts
If you don't know what is wrong with the SELECT commands, post both cased here together with the controller and model

Rails - saving checkbox values

Just trying to save the values of 4 checkboxes into a column named reminders to my Tickets Model.
But, either the values aren't being saved, or when I go back to edit this "Ticket" its not ale to pull the data from the db and display the true / false vaules correctly.
Any advice?
/tickets/_form.html.erb
<%= form_for(#ticket) do |f| %>
<div>
<% [ 'S.T.A.R.T', 'E.N.D.E.D', 'URGENT' , 'Repeat Request' ].each do |reminder| %>
<br><%= check_box_tag 'reminders', reminder, (params[:reminders] || {}).include (reminder) %>
<%= reminder.humanize %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Rather than using check_box_tag the way you are, change it to use your form builder object provided by form_for. It'll ensure that the name of the checkbox is correct which is your problem (I think).
Because you're not using it, the checkbox is probably taking on a different name to what rails is expecting to see, so when you submit the form, the param name won't be associated with your record and thus won't be changed. Try using
<%= f.check_box_tag :reminder %>
Rails will automatically handle whether or not it is ticked when the page loads :)

Resources