how to pass all student_id in checkbox - ruby-on-rails

I am having check box for selecting students in a particular class.But the unselected student id's are not passing via check box.Please help me. And also I have included coding below.
In View
<%= label_tag :students %>
<button type="button" id="check_all">
Check / Uncheck All
</button>
<table id = "mark">
<tr>
<td>
<table >
<thead>
<tr>
<td><strong>Students List</strong></td>
</tr>
</thead>
<tbody>
<% #student.each do |i| %>
<tr>
<td><%= check_box_tag :student, i.id %><%= i.first_name.capitalize %></td>
</tr>
<% end %>
</tbody>
</table>
<table>
<tr>
<td>
</tr>
</td>
</table>
</td>
</tr>
</table>
Js file
$('#check_all').on("click", function(){ $('input[type="checkbox"]').click(); });

You can achieve that in two ways at least.
one) deducting the submitted students from the students collection ids:
unselected_ids = #student.collect(&:id) - params[:student].collect(&:to_i)
two) setting another hidden field from client site using javascript

You can use hidden input with the same name before checkbox and zero value.
<input type='hidden' value='0' name='student'>
<input type='checkbox' value='1' name='student'>
When form submitted and checkbox is checked previous 0 value overwrites by 1. If checkbox not checked then 0 value sends to the controller.
Bur its works only if you have one value, but you have a lot of ids. And you must use student[] name in checkboxes, if you use student name then only last checked value sends in controller by in params[:student]
In this case use can use this construction in your code:
<% #student.each do |s| %>
<tr><td>
<%= hidden_field_tag "student_all[]", s.id %>
<%= check_box_tag "student[]", s.id %><%= s.first_name.capitalize %>
</td></tr>
<% end %>
And in controller get unchecked students like:
student_unchecked = params[:student_all] - params[:student]

Related

how to save variable number of arguments of same type and same name in Rails?

A form is submitted in rails which have variable number of invoiced items, with a boolean value as true or false.How can I get all these values and save them in the database in the respective fields:
Request parameters are as:
<ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"cCQjRuaHnsIkCaffZfi6t3err4YPxrEWXSXNKy4gFmDUOtWt+T4JALddxkJWo/7giXD3dNXlvJz9tJ0EYDKKjQ==",
"invoiced_186"=>"1", "invoiced_187"=>"1", "invoiced_188"=>"1",
"invoiced_189"=>"1", "invoiced_190"=>"1",
"commit"=>"save", "controller"=>"cader/caders", "action"=>"add_invoiced_items", "id"=>"63813"} permitted: false>
Form templated is as:
<%= form_with url: cader_add_invoiced_items_path(#job_checkout.id), local: true do |f| %>
<table class="table table-bordered table-striped">
<thead>
<th>Item #</th>
<th>File</th>
<th>Service</th>
<th>Price $USD</th>
<th>Invoice</th>
</thead>
<tbody>
<% #done_job.each do |done_job| %>
<tr>
<td>
<%= f.check_box :"invoiced_#{done_job.id}" %>
<label>
<%= done_job.id %>
</label>
</td>
<td><%= done_job.file_name %></td>
<td><%= done_job.service %></td>
<td>$<%= done_job.amount %></td>
<td></td>
</tr>
<% end %>
</tbody>
</table>
<%= f.submit 'save' %>
How to manage them in server side because the field inoice_x is variable in number.
You can name your checkboxes like this
<checkbox name="invoiced[]" value="187">
You should receive an array of values checked. (Sorry, I can't test it ATM)
[187, 188]
Or do this
<checkbox name="invoiced[187]" >
Then, I believe you'd receive a hash
{187 = 1, 188 = 1}

Pass html table td value to rails controller

In my html I'm displaying some data from two tables. I provided an edit button for each row of the table. When I click on it, it has to check if the name is existing in table1 or table2 and take all the details of that particular name.
HTML:
<div class="col-md-12">
<h5 style="text-align: center;">List of SNMP OIDs</h5>
<table id="myPersonTable" class="table table-striped" >
<thead>
<tr>
<th>Person Name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="table_body">
<% #all_persons.each do |person|%>
<tr>
<td>
<%= person['name'] %>
</td>
<td>
<%= link_to '<button type="button" class="btn btn-info">Edit</button>'.html_safe, edit_oid_path(person['id'])%>
</td>
<td>
<%= form_tag(contoller: "configuration", action: "delete_person") do%>
<%= hidden_field_tag(:person_id, person['id'])%>
<%=submit_tag "Delete", class: "btn btn-danger", data: {confirm: "Are you sure?"}%>
<% end %>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>
Rails Controller:
def edit
person_f = Person.find_by(name: params[:name])
person_s= HardPerson.find_by(name: params[:name])
if person_f.present?
#person = Oid.find(params[:id])
elsif person_s.present?
#oid = HardPerson.find(params[:id])
end
end
Here is a problem: I click on edit button for a person name from person2
table having id=1. This id exists in person1 and person2 tables both. Instead of taking details from person2 it is checking that id in person1 table and it is getting values for id=1 person details from person1 table
Here in controller params[:name] is getting null value. Help me to get params[:name] in my rails controller
To get params[:name] in your controller use the :param option in your routes to override the default resource identifier :id
resources :people, param: :name
This will allow you to use:
Person.find_by(name: params[:name])
Keep in mind that you might need to to override ActiveRecord::Base#to_param of a related model to construct a URL.
See 4.10 Overriding Named Route Parameters for more information.
It's a bit hard to understand what is your issue, but I'll try. Am I right that you want to see value from <%= person['name'] %> as a params[:name] inside edit action? Just pass it as additional argument to path helper:
<%= link_to '<button type="button" class="btn btn-info">Edit</button>'.html_safe,
edit_oid_path(person['id'], name: person['name'])%>

Rails and html form (materialize in this case)

I am creating a table for my Product model. As headers, I will have the attribute names, and in the body the rows will represent a record for which I want to add values and then save .At the moment, I'm sketching this up as a HTML/CSS ( with Materialize)
<table>
<thead>
<tr>
<th>#</th>
<th>Date</th>
<th>Document</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>12/12/2017</td>
<div>
<td>
<select class = "browser-default">
<option value="" disabled selected>Choose your option</option>
<option value ="1">Option 1</option>
<option value ="2">Option 2</option>
</select>
</td>
<td class ="input-field col s6" >
<input id="last_name" type="text" class="validate">
</table>
If I want to keep the provided option, input, checkboxes from materialize, how can I save my record ( I want to still use input-field for e.g. and the value that I put there to be saved)
How can I adapt this to Rails form?
You'll want something like this in a html.erb file:
...
<tbody>
<% #products.each do |product| %>
<tr>
<td><%= product.id %></td>
<td><%= product.your_date_column %></td>
<%= form_for product do |f| %>
<td>
<%= f.select :browser_default, [["Option 1", 1], ["Option 2, 2"]], include_blank: "Choose your option" %>
</td>
<td class ="input-field col s6" >
<%= f.input :last_name %>
</td>
<% end %>
...
Couple of things to note:
You'll need to set #products in the relevant controller action.
This then iterates through these, creating a row for each product.
You'll need a submit button for this form, or to establish how to submit using AJAX. The former is simpler and would just need <%= f.submit %> adding to the row.
Hope that helps - let me know how you get on or if you have any questions :)

How to Handle 2 tables with one form_tag? Rails 3

Beneficiaries
id (PK)
name
age
income
Beneficiary_loans
id (PK)
beneficiary_id (FK)
amount
rate
period
What I'm doing is, selecting a list of beneficiary from [Beneficiaries] table and displaying as follows
<%= form_tag({:action => 'update_survey_list_status', :status=>4}) do %>
<table width="100%">
<tr>
<th>Beneficiary Details</th>
<th>Amount</th>
<th>Rate</th>
<th>Period</th><th>
<input type='checkbox' name='checkall' onclick='checkedAll();'>
</th>
</tr>
<% #publishedlist.each do |b| %>
<tr>
<td><%= b.firstname %></td>
<%= fields_for :beneficiaryloan do |bloan| %>
<td> <%= bloan.text_field :amount%></td>
<td> <%= bloan.text_field :rate%></td>
<td> <%= bloan.text_field :period%></td>
<% end %>
<td><%= check_box_tag "benificiary_ids[]",b.id, :name => "benificiary_ids[]"%> </td>
</tr>
<% end %>
</table> <%= submit_tag "Approve", :class=>'form_buttons' %>
<% end %>
In controller,
#beneficiaries=Beneficiary.find(:all, :conditions => ["id IN (?)", params[:benificiary_ids]])
#beneficiaries.each do |b|
#beneficiaryloan = Beneficiaryloan.new(params[:beneficiaryloan])
#beneficiaryloan.beneficiary_id=b.id
#beneficiaryloan.hfi_id=session[:id].to_s
#beneficiaryloan.status_id=params[:status]
#beneficiaryloan.save
end
What I'm not getting is
params[:beneficiaryloan]
Values are coming as NULL
Am I missing something here in this form?
Check the following,
With the help of any browser tool(eg:firebug), make sure that the form has been rendered properly. Sometimes due to some misplaced tags(generally happens with table structure) the form does not renders properly.
Try to remove the table structure and see if the form works.
Make sure your association is fine, i guess it should be Beneficiary has many Beneficiaryloan
If none of the above helps, please post the request parameters over here.

Rails Update Single Attribute with Multiple Fields

I'm currently trying to make a form called countcash that allows users to input the actual number of quarters, dimes, nickels, pennies, twenties, tens, fives, ones and then the monetary value of any other items in the cash box and then when they hit submit, I want to total those values and set the cashstart field of my current shift record.
The real issue is that I'm not sure what my form is supposed to look like and how the controller/model are supposed to be setup in this instance.
I have a shift_id saved in a session[:shift_id] variable and the shift with that id is the shift that I want to modify with the calculated cashstart.
What does the <%= form_for %> tag need to look like if I want to follow the MVC correctly and how do I set up the controller/model to update the database with the calculated value? And what should I be setting the route to? I can't find anything like this on either stack overflow or other rails forums (Although you'd think that modifying a single attribute through multiple text fields would be pretty straight forward)
Just as a reference, this is the form I was using previously (To no avail)
app/views/countcash.html.erb
<%= form_for #shift do |f| %>
<table>
<tr>
<th>Coins</th>
<th></th>
</tr>
<tr>
<td>Quarters: </td>
<td><%= f.text_field :quarters %><br /></td>
</tr>
<tr>
<td>Dimes: </td>
<td><%= f.text_field :dimes %><br /></td>
</tr>
<tr>
<td>Nickels: </td>
<td><%= f.text_field :nickels %><br /></td>
</tr>
<tr>
<td>Pennies: </td>
<td><%= f.text_field :pennies %><br /></td>
</tr>
<tr>
<th>Bills</th>
<th></th>
</tr>
<tr>
<td>Twenties: </td>
<td><%= f.text_field :twenties %><br /></td>
</tr>
<tr>
<td>Tens: </td>
<td><%= f.text_field :tens %><br /></td>
</tr>
<tr>
<td>Fives: </td>
<td><%= f.text_field :fives %><br /></td>
</tr>
<tr>
<td>Ones: </td>
<td><%= f.text_field :ones %><br /></td>
</tr>
<tr>
<th>Other</th>
<th></th>
</tr>
<tr>
<td>Value (in $): </td>
<td><%= f.text_field :others %><br /></td>
</tr>
</table>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And here's my shifts_controller that doesn't do anything at the moment, since I'm not sure how I need to go about updating the attribute after the submit button is clicked
def countcash
#shift = Shift.find(session[:shift_id])
redirect_to(login_path)
end
I think you are almost there, presumably you have a named route which allows you to do this as your form declaration:
<%= form_for #shift, :url => countcash_shift_path(#shift) do |f| %>
If in doubt, run rake routes in your console to determine if such routes exist. If it doesn't, perhaps you would want to explore RESTful routes, which should look something like this in your routes.rb:
resources :shifts
Inside the countcash action in your controller, it's just a matter of doing this:
#shift = Shift.find(session[:id])
#shift.update_attributes(params[:shift]
This should work assuming that you have you have set up RESTful routes for your shift resource. Also, I am assuming that your model/database is set up with quarters, dimes, etc as individual fields (otherwise you will require some more advanced than update_attributes).
Since you are not having these individual fields in the database (as per your comment), you should not be putting as part of the model's form. So instead of:
<%= f.text_field :dimes %>
You'd do something like:
<%= text_field_tag :dimes, params[:dimes] %>
And inside your controller, you can just access them like so:
params[:dimes] + params[:quarters] # multiply as per currency logic
If you want to get a little more fancy, what you could do is write methods that take in these values, so you still leave the form as your current state, but add methods that take in the values and do something with it like so (for all types of currency, not just dimes):
def dimes=(value)
#running_total += value
end
In your controller, do this instead:
#shift.attributes = params[:shift]
So what happens is that when you pass your model the hash of attributes, it will try to assign the values based on the symbol names. So the value of dimes in params will be passed in as if this was being called:
#shift.dimes = params[:shift][:dimes]
I think that should work for you, assuming that you use #running_total for something. You could use #amount or something if that's what you already have as a model attribute.

Resources