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'])%>
Related
I am displaying table records from an array in a view, but have added delete and edit buttons to each row, in which I want to be able to delete the dynamically instantiated table row when the delete button is pressed, as well as the array item from the array that populated it. I want the page to refresh as well.
Past attempts:
I have tried creating forms with submit_tags for deleting, but to no avail, as well as routing and creating destroy and delete functions. I have looked up solutions to this for hours but none worked for me.
I am a beginner at Ruby. The code is a bit untidy due to me having inserted solutions, trying to test them, and then deleting.
CODE:
I have created an array in my controller called #db_data, where a search button only displays specific elements with #hospital_data:
class HospitalsController < ApplicationController
def index
#ONLY CHANGE THIS TO DATABASE DATA IN 3D ARRAY FORMAT!!
#db_data=[["1","Helen Joseph"],["2","Bara"],["3","Charlotte Maxeke"]]
#Format is [[hospital ID], [hospital name]]
#SEARCH BAR CODE
#DON'T CHANGE BELOW CODE!!==========================
#data = params[:searchHospitals]
if #data.blank?
#hospitals_array=#db_data
else
#hospitals_array=#db_data.select{|x,y| y.match(/#{#data}/) }
end
#===================================================
end
end
The html.erb file just for the display table is as follows:
<!--TABLE-->
<div class="m-4">
<table id="cartTable" class="table">
<thead>
<tr>
<th scope="col">Hospital ID</th>
<th scope="col">Hospital Name</th>
</tr>
</thead>
<tbody>
<!--loop through each item in hospital array-->
<% #hospitals_array.each_with_index do |hosp_element, index| %>
<tr>
<th scope="row" class="col-5" > <%= hosp_element.first %> </th>
<td class="col-6"><%= hosp_element.last %> </td>
<!--edit and delete functionality-->
<td class="col-1">
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-outline-dark" >Edit</button>
<button type="button" class="btn btn-outline-dark" >Delete</button>
</div>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>
My route for this is currently:
get "/hospitals",to: "hospitals#index"
Well I am not sure if I understand your problem in 100% but I guess you want to add edit and delete buttons to your view.
To delete your rows we have to add few things, at first let's update routes.rb file:
# For explanation I recommend: https://guides.rubyonrails.org/routing.html
resources :hospitals, only: [:index, :destroy]
then we need to define controller actions for our new routes, I've also refactored your Index action to use ActiveRecord:
class HospitalsController < ApplicationController
def index
#hospitals = Hospital.select(:id, :name)
if params[:searchHospitals]
# It's better to use DB engine for optimization instead of Ruby `.select`
#hospitals = #hospitals.where("NAME like '%#{params[:searchHospitals]%'")
end
end
def destroy
#hospital = Hospital.find(params[:id])
#hospital.destroy
redirect_to(hospitals_path)
end
end
and finally in the view
<% #hospitals.eachx do |hospital| %>
<tr>
<th scope="row" class="col-5" > <%= hospital.id %> </th>
<td class="col-6"><%= hospital.name %> </td>
<td class="col-1"><%= link_to 'Destroy', micropost, :confirm => 'Are you sure?', :method => :delete, class: 'btn btn-outline-dark' %></td>
</tr>
<% end %>
For edit button you'll have to create another methods in controller and add additional views.
I am using cocoon on one of forms and i want to add a show button to each row which will direct users to another model's show page. However, while everything is working smoothly i can not make this button to show up.
So this my current view:
<div class = "nested-fields">
<div class="table-responsive">
<table class= "table table-hover">
<tr>
<th> Product ID </th>
<th> Button </th>
</tr>
<tr>
<td> <%=f.object.product_id%> </td>
<td> <%= link_to 'Show', product_path(f.object.product_id), class: "btn btn-outline-success", target: :_blank %> </td>
</tr>
</table>
</div>
</div>
When i try to open this page, i am getting this error:
No route matches {:action=>"show", :controller=>"products", :id=>nil}, missing required keys: [:id]
However, i know that product_id is not nill because, on the table i can print the product_id for each line. And, my product routes are definitely fine, i can already use them including with show action. And i know that product_id has a matching id in products table.
Also, if try to go to products' index page by using:
<%= link_to 'Show', products_path(f.object.product_id), class: "btn btn-outline-success", target: :_blank %>
the following url is going to be generated:
http://localhost:3000/products.97
I just cannot understand why it cannot get the id when i use it product_path.
Any help will be regarded.
Thanks.
From the conversation/comments I can only conclude one of the items product_id is actually really nil. Easy way to make sure your table/page still renders is write your view as follows
<td>
<% if f.object.product_id.present? %>
<%= link_to 'Show', product_path(id: f.object.product_id), class: "btn btn-outline-success", target: :_blank %>
<% end %>
</td>
I have a form_tag with a radio_button_tag and it populates with data from DB. It must simply be directed to a customised update action(update_multiple) where a boolean column is updated for all those 2 records which have been changed in the form.
For e.g. say when initially the form was populated from DB with record 1's radio button selected and now user changed his selection to record 3, then at Submit of form tag the update of both records must occur but the problem is the code at submit, only collects id of record which is now selected in that group.How do I get id of that record also which was unselected so that I can update_all for both of them at one go?
And if Submit cannot handle this action, then is there a way in controller or form to persist the id of the initial selected record before populating the form? As you see, I've tried with collecting an array of ids[] with radio_button_tag.
TIA for your help.
Here's the form code:
<%= form_tag update_multiple_user_cv_attachments_path, method: :put, action: :update_multiple do %>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th> Select a CV </th>
<th> Resume Name </th>
</tr>
</thead>
<tbody>
<% #cv_attachments.each do |cv_attachment| %>
<%= hidden_field_tag cv_attachment.main, :value => params[:main] %>
<tr>
<td><%= radio_button_tag "cv_attachment_ids[]", cv_attachment.id, cv_attachment.main %> </td>
<td><%= cv_attachment.attachment.file.basename %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= submit_tag "Select Main", :class =>'button' %>
<% end %>
Here's the controller update_multiple code.
def update_multiple
CvAttachment.update_all(["updated_at=?", Time.now], :id => params[:cv_attachment_ids])
end
I can think of 2 ways to achieve your objective.
update the boolean for all the attachments which belong to the user to false and then update the one which has been selected to true
include a hidden field in the form and set it to the id that is already true. Then in the controller action, update the one that is selected to true and the one in the hidden field to false. This is probably a better option and you'll probably want to wrap the d/b updates in a transaction.
<tbody>
<% #cv_attachments.each do |cv_attachment| %>
<% if cv_attachment.main %>
<%= hidden_field_tag "ex_main_cv", cv_attachment.id %>
<% end %>
<tr>
<td><%= radio_button_tag "main_cv", cv_attachment.id, cv_attachment.main %> </td>
<td><%= cv_attachment.attachment.file.basename %></td>
</tr>
<% end %>
</tbody>
controller
def update_main_attachment // probably a better name for this method
if params["ex_main_cv"] != params["main_cv"]
Attachment.transaction do
deselected_attachment = Attachment.find(params["ex_main_cv"]
deselected_attachment.update_attribute(:main, false)
selected_attachment = Attachment.find(params["main_cv"]
selected_attachment.update_attribute(:main, true)
end
end
end
Many thanks #margo. Here' how I resolved it partly your way of using hidden_field. But for now keeping this thread open as I'm making 2 DB updates for toggle of same column.
<tbody>
<% #cv_attachments.each do |cv_attachment| %>
<% if cv_attachment.main %>
<%= hidden_field_tag "ex_main", cv_attachment.id %>
<% end %>
<tr>
<td><%= radio_button_tag "new_main", cv_attachment.id, cv_attachment.main, :id => "#{cv_attachment.id}"%> </td>
<td><%= cv_attachment.attachment.file.basename %></td>
</tr>
<% end %>
</tbody>
and in controller:
def update_main
if request.put?
if params["ex_main"] != params["new_main"]
CvAttachment.find(params[:ex_main]).toggle!(:main)
CvAttachment.find(params[:new_main]).toggle!(:main)
end
end
I've got a method named 'statement' in a balances controller (balances_controller.rb) that returns information from a specific date (#latestDate) to a view (statement.html.rb)
#latestDate = the most recent date in the 'date' column in the 'balances' table
In the view, I've also got a dropdown list of all the dates and when a date is selected, I'd like to be able to update the information so that in effect, the statement method is called again but the #latestDate is set to the selected value from the dropdown list.
How can I do this?
UPDATE:
I've modified my code with brito's suggestions. When I press the Search button, the form passes the following params:
?utf8=✓&date_id=30%2F12%2F2015&commit=Search
However, if I select a date and click Search, the #latestDate gets set and the h1 tag gets displayed correctly, but the rest of the data doesn't get returned.
CODE:
balances_controller.rb
....
def statement
#dates = Balance.select("distinct(date)").order('date desc')
#Updated
if (params[:date_id].blank?)
#latestDate = Balance.order('date desc').first.date
else
#latestDate = params[:date_id]
end
#summaryBalances = Balance.joins(:account).order('accounts.credit').where('date = :abc', {abc: #latestDate})
end
....
balances/statement.html.rb
....
<h1>Statement at <%= #latestDate %></h1>
#UPDATED
<%= form_tag("/statement", method: "get") do %>
<%= select_tag "date_id", options_for_select( #dates.collect {|d| [ d.date, d.date ] }) %>
<%= submit_tag("Search") %>
<% end %>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Account</th>
<th>Balance</th>
<th colspan="1"></th>
</tr>
</thead>
<tbody>
<% #summaryBalances.each do |balance| %>
<tr>
<td><%= balance.account.name %></td>
<td class='account-balance'><%= number_to_currency(balance.balance, unit: "£") %></td>
<td><%= link_to 'Edit', edit_balance_path(balance) %></td>
</tr>
<% end %>
</tbody>
</table>
</div>
....
A "dropdown" is a kind of input (HTML <select>).
<input>s and <select>s must be within a <form> HTML element.
Using pure HTML
Whatever is in the <form> will be accessible in the params hash. So if you have a dropdown list, it should be within a <form> like this:
<form accept-charset="UTF-8" action="/yourroute" method="get">
<select name="car">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</form>
In the example above, the selected value (e.g. "volvo") will be available in the controller within params["car"]. Note that you would still have to define /yourroute.
Using Rails' helper methods
Of course, Rails helps you generate forms and inputs. You can use Rails' form helpers for that. For example, the following generates a search form ("Search" label, text box for input and a button) that sends a GET to the /search route:
<%= form_tag("/search", method: "get") do %>
<%= label_tag(:q, "Search for:") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>
EDIT
To check and set #latestDate = balance[date_id] if the balance[date_id] was selected:
#latestDate ||= params[:balance[date_id]] unless params[:balance].blank?
Basically I'm trying to list all events from my database on a website using this code:
<table class="table">
<thead>
<tr>
<th>Event</th>
<th>Join Event?</th>
</tr>
</thead>
<tbody>
<% #events.each do |e| %>
<p>
<tr>
<td>
<div>
<%= e.name %>
</div>
</td>
<td>
<div class="btn-group" data-toggle="buttons-radio">
<button class="btn" class-toggle="btn-success"><i class="icon-ok"></i></button>
<button class="btn btn-danger active" class-toggle="btn-danger"><i class="icon-remove"></i></button>
</div>
</td>
</tr>
</tbody>
<% end %>
</table>
You can easily join an event by clicking on a radio button. Now my problem is how can I save this form in Rails? In this example I have joined(=clicked) Event 2. What is the best way to save this form back into the database. Ideally I have a "Update" or "Save" button at the end of the website, which does that for me.
But when I add a simple submit button like this to the my form
...same code as above
</td>
</tr>
</tbody>
<%= f.submit 'Save form' %>
<% end %>
</table>
then my submit button will be triggered everytime I click on one of my radio buttons. Does anyone know a fix to this problem?
well, it is fairly simple to do a event[] radio button that when submitted will submit an array of the selected options.
The button tags would look like this, adjusting for your classes etc.
<%= radio_button_tag event[], e.id %>
then the controller would look like
def create
...
user.events = params[:event] unless params[:event].empty?
user.save
...
end
This ofcoarse assumes that you have a column in your user model to store events they are going to. A more flexible model would be to have user :has_many events :through => user_events. The same controller logic would apply, except it would look like
def create
...
if params[:event]
params[:event].each do |e|
user.user_event.new(:event_id => e)
end
end
....
end
Resources:
Form tag helpers: here
Using :has_many :through associations : here (section 2.4)