Add link to methods to array in controller - ruby-on-rails

I have a index method in my rails 4 application controller that looks like:
def index
#products = Product.all
#headers = #products.map(&:data).flat_map(&:keys).uniq
#product_data = #products.map{ |product| product[ :data ].values }
end
So #product_data ends up with something like:
[["Table", "$199.99", "blue"], ["Book", "$9.99", "green"]]
In my view, I put all of this in a unordered list. But now I'd like to have a link_to an edit and delete page for each product. How can I include this in my array, so I can display a link for each product on the view page?

You could add product_id to the result of product[:data].values array. Then use that product_id as parameter to your product url_helpers.
#product_data = products.map{ |product| product[ :data ].values.unshift(product.id) }
This should give you something similar to:
[[1, "Table", "$199.99", "blue"], [2, "Book", "$9.99", "green"]]

I see there is no use of #product_data there.Why can't You display the data in a table in your index.html.erb and you can loop through every product,so that the edit and delete links appear to every product.Assuming that you have name,price and color attributes for your product model,just do like this
In your index.html.erb:
<table border=1>
<tr>
<th>Product Name</th>
<th>Product Price</th>
<th>Product Color</th>
<th></th>
<th></th>
</tr>
<% #products.each do |p| %>
<tr>
<td><%=p.name %></td>
<td><%=p.price %></td>
<td><%=p.color %></td>
<td><%=link_to 'Edit', :action => "edit", :id => p.id %></td>
<td><%=link_to 'Delete', :action => "delete", :id => p.id, :confirm => "Are you sure?" %></td>
</tr>
<% end %>
</table>
Note:
Its just an another approach.

Related

Rails - Redirect to specific record page

I'm pretty new to Ruby on Rails and Ruby in general but I'm trying to make a small website with simple database in Ruby on Rails.
At the moment I have the html.erb pages to show, add and edit records.
The next thing i wanted to do is the action that redirects user to a page with more info about the record he clicked in the record table.
I can't really think of any way to do this.
Any help would be really appriciated.
p.s. Sorry for any mistakes in my English - it's not my first language and im still learning!
Here is my html code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tablecontainer">
<table class="table table-bordered table-condensed">
<tr class="success">
<td><b>Nazwa</b></td>
<td><b>Obrażenia</b></td>
<td><b>Typ</b></td>
<td><b>Waga</b></td>
<td><b>Zasięg</b></td>
<td><b>Szybkość</b></td>
<td><b>Rzadkość</b></td>
<td><b>Opcje</b></td>
</tr>
<% #biala.each do |b| %>
<tr>
<td><%= b.nazwa %></td>
<td><%= b.obrazenia %>%</td>
<td><%= b.typ %></td>
<td><%= b.waga %></td>
<td><%= b.zasieg %></td>
<td><%= b.szybkosc %></td>
<td><%= b.rzadkosc %></td>
<td><%= link_to '', {id: b.id, action: 'db_wiecejbiala'}, class: "glyphicon glyphicon-info-sign" %><%= link_to '', {id: b.id, action: 'db_edytujbiala'}, class: "glyphicon glyphicon-pencil" %> <%= link_to '', {id: b.id, action: 'usunbiala'}, data: {confirm: 'Jesteś tego pewien?'}, class: "glyphicon glyphicon-remove" %></td>
</tr>
<% end %>
</table>
And here is the controller:
class BazaController < ApplicationController
def db_bronbiala
#biala = BronBiala.all
#iloscbiala = BronBiala.count
end
def db_dodajbiala
#nowybiala = BronBiala.new
end
def utworzbiala
#nowybiala = BronBiala.new(parametrybiala)
if #nowybiala.save
redirect_to(action: 'db_bronbiala')
else
render('db_dodajbiala')
end
end
def parametrybiala
params.require(:bron_biala).permit(:nazwa, :obrazenia, :typ, :waga, :zasieg, :szybkosc, :rzadkosc, :zalety, :wady, :ciekawostki, :opis)
end
def usunbiala
usuwaniebiala = BronBiala.find(params[:id]).destroy
#biala = BronBiala.all
render('db_bronbiala')
end
def db_edytujbiala
#biala = BronBiala.all
#edytowanabiala = BronBiala.find(params[:id])
end
def aktualizujbiala
#biala = BronBiala.all
#edytowanabiala = BronBiala.find(params[:id])
if #edytowanabiala.update_attributes(parametrybiala)
redirect_to(action: 'db_bronbiala')
else
render('db_edytujbiala')
end
end
def db_wiecejbiala
#biala = BronBiala.all
#bialawiecej = BronBiala.find(params[:id])
end
end
And the db_bialawiecej code:
<div class="content">
<h2>Lista:</h2>
<div class="tablecontainer">
<table class="table table-bordered table-condensed">
<tr class="success">
<td><b>Nazwa</b></td>
<td><b>Obrażenia</b></td>
<td><b>Typ</b></td>
<td><b>Waga</b></td>
<td><b>Zasięg</b></td>
<td><b>Szybkość</b></td>
<td><b>Rzadkość</b></td>
</tr>
<% #bialawiecej.id do |b| %>
<tr>
<td><%= b.nazwa %></td>
<td><%= b.obrazenia %>%</td>
<td><%= b.typ %></td>
<td><%= b.waga %></td>
<td><%= b.zasieg %></td>
<td><%= b.szybkosc %></td>
<td><%= b.rzadkosc %></td>
</tr>
<% end %>
</div>
</div>
On click send id of clicked item (GET). you will have link similar to : localhost:3000/desired_model/5
then in action do #desired_model = DesiredModel.find(params[:id])
redirect user to desired show page.
Show data.
Next time please provide some code :)

Submit multiple entries to database, from an array, in Rails on the same page

I'm trying to submit multiple entries into the database from an array. So, I create multiple new entries and store them in an array. In the view, I have a form of checkboxes for the user to check which ones he/she wants to add to the database. Upon clicking submit, I would like to add each of these forms to the database all in on shot. Here is the code:
Controller:
class EventsBoysController < ApplicationController
def new
#season = find_season
#meet = find_meet(#season)
#athletes_boys = current_coach.athletes.where(boy: true)
#events_boys = []
#athletes_boys.each do |athlete|
#events_boys << #meet.events_boys.new(:athlete_id => athlete.id)
end
#events = ["400 IH", "100", "1600", "400", "110 HH", "800", "3200", "200"]
end
def create
debugger
#season = find_season
#meet = find_meet(#season)
#events_boys = #meet.events_boys.create(events_boy_permit)
# debugger
if #events_boys.save
redirect_to #events_boys, notice: 'Season was successfully created.'
else
render action: "new"
end
end
private
def find_season
Season.find(params[:season_id])
end
def find_meet season
season.meets.find(params[:meet_id])
end
def events_boy_permit
params.require(:events_boy).permit(:season_id, :meet_id, :athlete_id, :boys_400_m_im, :boys_1600_m, :boys_400_m, :boys_110_m_hh, :boys_800_m, :boys_3200_m, :boys_200_m, :boys_100_m, :time_400_m_im, :time_1600_m, :time_400_m, :time_110_m_hh, :time_800_m, :time_3200_m, :time_200_m, :time_100_m, :place_400_m_im, :place_1600_m, :place_400_m, :place_110_m_hh, :place_800_m, :place_3200_m, :place_200_m, :place_100_m)
end
end
View:
<h1><%= "Create new events for the boys for #{#meet.name}" %></h1>
<table id="events-table">
<tr>
<th></th>
<% #events.each do |event| %>
<th><%= event %></th>
<% end %>
</tr>
<% #events_boys.each do |event| %>
<tr>
<td><%= Athlete.find_by_id(event.athlete_id).name %></td>
<%= form_for [#season, #meet, event], :html => { :mulitpart => true } do |f| %>
<td><%= f.check_box :boys_400_m_im %></td>
<td><%= f.check_box :boys_100_m %></td>
<td><%= f.check_box :boys_1600_m %></td>
<td><%= f.check_box :boys_400_m %></td>
<td><%= f.check_box :boys_110_m_hh %></td>
<td><%= f.check_box :boys_800_m %></td>
<td><%= f.check_box :boys_3200_m %></td>
<td><%= f.check_box :boys_200_m %></td>
<td><%= f.submit "Submit", :class => 'btn' %></td>
<% end %>
</tr>
<% end %>
</table>
<script type="text/javascript">
var athletes = new Array();
var arrayInAthletes = new Array();
element = document.getElementById("events-table");
var athletesArray = element.children[0].children
for (i=1; i < athletesArray.length; i++) {
var rowArray = athletesArray[i].children;
arrayInAthletes = [];
arrayInAthletes[0] = rowArray[0].innerText;
var sum = 0;
for (j=1; j < rowArray.length; j++) {
var checkBox = rowArray[j].children[0];
var checkedValue = $('#'+checkBox.id+':checked').val();
if (checkedValue === "1") {
arrayInAthletes[sum+1] = rowArray[j].children[0].id;
sum += 1;
}
}
athletes[i-1] = arrayInAthletes;
}
</script>
I think what you are looking for is something like the code below (needs to be adapted to your example).
Contact.create([
{first_name: 'Ryan', last_name: 'Smith', email: 'ryan#smith.com'},
{first_name: 'John', last_name: 'Doe', email: 'john#doe.com'}
])
All you need to do is put your data into an array of hashes. Each hash is an object you want to save. This will do a batch insert, which is what I think you want.
You will need to pull the values for checked/unchecked from your params since that is where they are passed to your controller. Cycle through that hash and perform your logic on that.

Cannot go to show action nested resources

student_classes_controller.rb
class StudentClassesController < ApplicationController
before_filter :set_batch
def index
#sections = StudentClass.all
end
def show
#section = StudentClass.find(params[:id])
end
private
def set_batch
#batch = Batch.find(params[:batch_id])
end
end
in the view of student_classes/index.html.erb
<table class="table table-bordered table-hover">
<thead bgcolor="#B7B7B7">
<th>Section</th>
<th>Number of Students</th>
<th>Details</th>
</thead>
<% #sections.each do |section| %>
<tr>
<td><%= section.name %></td>
<td><%= section.students.count %></td>
<td><%= link_to 'View Details', batch_student_classes_path(#batch , section) %></td>
</tr>
<% end %>
</table>
the url of view details is this http://localhost:3000/batches/1/student_classes.1
but i want to make it as this http://localhost:3000/batches/1/student_classes/1
routes.rb
resources :batches do
resources :student_classes
end
rake routes
batch_student_classes GET /batches/:batch_id/student_classes(.:format) student_classes#index
POST /batches/:batch_id/student_classes(.:format) student_classes#create
new_batch_student_class GET /batches/:batch_id/student_classes/new(.:format) student_classes#new
edit_batch_student_class GET /batches/:batch_id/student_classes/:id/edit(.:format) student_classes#edit
batch_student_class GET /batches/:batch_id/student_classes/:id(.:format) student_classes#show
PUT /batches/:batch_id/student_classes/:id(.:format) student_classes#update
DELETE /batches/:batch_id/student_classes/:id(.:format) student_classes#destroy
The path method you want to call is batch_student_class_path not batch_student_class*es*_path.

update_attributes is not working

Here's my controller
class ActivitiesController < ApplicationController
def exercises
if current_user.userprofile.present? #chef whether there is a userprofile object
#weeknum = current_user.userprofile.week
#dayly_activity = Activity.where(:week => 1, :day => 'Monday').first
end #end check userprofile
end
def updatexercises
respond_to do | format |
#dayly_activity = Activity.where(:week => 1, :day => 'Monday').first
#dayly_activity.update_attributes(params[:#dayly_activity])
#dayly_activity.save
format.html { render action: "exercises" }
end
end
end
And my template
<h1>WEEKLY EXERCICES</h1>
Day : <%= #dayly_activity.day %>
<%= form_for(#dayly_activity, :url => { :action => "updatexercises" }) do | f | %>
<table>
<tr>
<td>Jogging:</td>
<td>
<% list = (0..20).to_a %>
<%= f.select :jog, list %>
x 0.1 km
</td>
</tr>
<tr>
<td>Bicycling:</td>
<td>
<% list = (0..10).to_a %>
<%= f.select :bicycl, list %>
km
</td>
</tr>
<tr>
<td>Push ups:</td>
<td>
<% list = (0..20).to_a %>
<%= f.select :pushups, list %>
x 10 times
</td>
</tr>
<tr>
<td colspan = "2"><%= f.submit %></td>
</tr>
</table>
<% end %>
When I click the button, the Daily+activity object is not being saved. Am I missing some thing
EDIT
I've tried to hard code this way and it saving to the database.
#dayly_activity.jog = 17
#dayly_activity.pushups = 13
#dayly_activity.save
Obviously, the problem must be with the update_attributes
You need to use params[:dayly_activity] (drop the # sign).
Also, I would put these two lines :
#dayly_activity = Activity.where(:week => 1, :day => 'Monday').first
#dayly_activity.update_attributes(params[:dayly_activity])
Outside of your respond_to block (put them on top of it).
You can also drop the #dayly_activity.save, update_attributes do it automatically and will returns true/false if it works/fails.
You have error in [:#dayly_activity]
And in that code
#dayly_activity.update_attributes(params[:#dayly_activity])
#dayly_activity.save
save is useless. update_attributes saving the record.
It better to check result of update_attributes. So you can catch validation errors.
For example
if #dayly_activity.update_attributes(params[:dayly_activity])
redirect_to dayli_activity_path, :notice => "Updated"
else
render :edit
end

With Gmaps4rails, how can I display a list of locations that are currently visible in the map view?

I am using gmaps4rails. I am trying to achieve the following: The map is showing locations with markers and the user can zoom/move his window of sight as he wishes. What I want is that as he does so, a list next to the map should dynamically update with all the locations that are currently visible.
I tried using the callback mechanism and getBounds to filter a data structure of what is visible, but without success.
How can I go about it?
Thanks a lot!
Julian
In my controller: class LocationsController < ApplicationController
def index
if (params[:sw_y] && params[:sw_x] && params[:ne_y] && params[:ne_x])
bounds = [ [params[:sw_x].to_f, params[:sw_y].to_f],
[params[:ne_x].to_f, params[:ne_y].to_f] ]
#locations_within_bounds = Location.within_bounds(bounds)
else
#locations_within_bounds = Location.all
end
#locations = Location.all
#json = Location.all.to_gmaps4rails
And in my view:
<%= gmaps("markers" => {"data" => #json, "options" => {"list_container" => "markers_list", "do_clustering" => true } } ) %>
<table>
<tr>
<th>Name</th>
<th>Address</th>
<th>Longitude</th>
<th>Latitude</th>
<th></th>
<th></th>
<th></th>
</tr>
<% #locations_within_bounds.each do |location| %>
<tr>
<td><%= location.name %></td>
<td><%= location.address %></td>
<td><%= location.longitude %></td>
<td><%= location.latitude %></td>
</tr>
<% end %>
</table>

Resources