Grouping records by user in Admin view - ruby

I would like to get all records with their usernames when signed in as Admin. For that my controller code is as below;
amol361s_controller.rb
def index
if current_user.admin
#amol361s = Amol361.all.search(params[:search]).order("created_at ASC")
#users = User.all.amol361s
else
#amol361s = current_user.amol361s.all.search(params[:search]).visible.order("created_at ASC")
end
respond_to do |format|
format.html
format.js
end
end
index.html.erb
<tbody id = "kola">
<% #users.each do |user| %>
<%= user.amol361s.each do |amol361| %>
<tr class="tr-<%= cycle('odd', 'even') %>" id='<%= "tr_#{amol361.id}" %>'>
<% if current_user && current_user.admin %>
<td class="col-1"><%= link_to amol361.date.try(:strftime,'%d/%m/%Y'), edit_amol361_path(amol361) %></td>
<% else %>
<td class="col-1"><%= amol361.date.try(:strftime,'%d/%m/%Y') %></td>
<% end %>
<td class="col-3"><%= span_with_possibly_red_color amol361.description %></td>
<td class="col-1"><%= number_with_precision(amol361.amount, :delimiter => ",", :precision => 2) %></td>
<td class="col-1 neg"><%= number_with_precision(amol361.discount, :delimiter => ",", :precision => 2) %></td>
<td class="col-1 neg"><%= number_with_precision(amol361.paid, :delimiter => ",", :precision => 2) %></td>
<% #balance += amol361.amount.to_f - amol361.discount.to_f - amol361.paid.to_f %>
<% color = #balance >= 0 ? "pos" : "neg" %>
<td class="col-1 <%= color %>"><%= number_with_precision(#balance.abs, :delimiter => ",", :precision => 0) %></td>
<td class="col-1"><%= amol361.delndel %></td>
<td class="col-1"><%= amol361.remark %></td>
<% if current_user && current_user.admin %>
<td class="col-1"><%= link_to "Hide", hide_amol361_path(amol361), method: :put, remote: true, style: "color:#bb7272;" %>
<%= link_to amol361, method: :delete, data: { confirm: "Are you sure?" }, :class => 'delete_item' do %>
<i class="fa fa-trash" ></i>
<% end %>
</td>
<% end %>
</tr>
<% end %>
<% end %>
</tbody>
Right now I am getting the error as undefined method amol361s' for # User::ActiveRecord_Relation:0x00007f5dec19d088.
So, I am trying to get the records followed by usernames, similar to how we gather records based on month.
Any suggestions are most welcome.
Thank you in advance.

From what I understand, you can simply eager load user records if the current user is admin, like this:
#amol361s = Amol361.includes(:user).search(params[:search]).order("created_at ASC")
If you do this, it will be effective to fetch the user data simply by calling association on each member of this relation, like this:
# example:
#amol361s.first.user.username # or whatever the name of username column is
I'm not sure I understood your question correctly though, cause it's a little bit unclear to me.

Related

approve multiple records at once

how to achieve this Scenario:
admin to select multiple records using a checkbox and click a button to approve selected, which will change the status of the selected items to approved at once. records are like posts.
here is my code:
config/routes:
resources :time_cards do
collection do
get 'management'
put 'approve_multiple'
end
member do
get 'review'
get 'tracking'
patch 'approve_or_reject'
end
end
html:
<%= form_tag({controller: 'time_cards', action: 'approve_multiple'}, method: 'put', id: 'approve_multiple_time_card_form') do %>
<% #time_cards.each do |time_card| %>
<tr>
<% if time_card.status.downcase == 'submitted' %>
<td><%= check_box_tag "time_cards_to_approve[]", time_card.id %></td>
<% else %>
<td> </td>
<% end %>
<td><%= time_card.id %></td>
<td><%= time_card.week_of.to_date.strftime('%B %-d, %Y') %></td>
<td><%= time_card.user.name %></td>
<td><%= time_card.status %></td>
<td><%= output_hours(time_card.time_card_entries) %></td>
<td>
<%= link_to review_time_card_path(time_card) do %>
<% if time_card.status.downcase == 'submitted' %>
<i class="material-icons">edit</i>
<% end %>
<% end %>
</td>
</tr>
<% end %>
<%= submit_tag "Approve Selected", class: 'btn btn-success' %>
<% end %>
controller:
#PUT /time_cards/approve_multiple
def approve_multiple
authorize TimeCard
#time_cards.update_all({status: 'Approved'}, {id: params[:time_cards_to_approve]})
respond_to do |format|
if !#time_cards.errors
format.json { render json: { notice: 'Time cards approved successfully.'} }
format.html { redirect_to redirect_to management_time_cards_path, notice: 'Time cards approved successfully.'}
else
format.json { render json: { error: #time_cards.errors, alert: 'There was a problem approving the time card.'}}
format.html { redirect_to management_time_cards_path, alert: #time_cards.errors}
end
end
end
??? I don't no where it is wrong?
Send these ids to an action like this
Post.where(id: params[:ids]).update_all(approved: true)
params[:ids] is an array of posts' ids
update_all returns the number of the updated records
Ops, I took for granted we were talking about rails but it's never mentioned.

How do I create a table to display all the instances of my Ruby class using ERB?

My table has the following columns:
<tr>
<th>Number</th>
<th>User</th>
<th>Password</th>
<th>UID</th>
<th>GID</th>
<th>GCOS</th>
<th>Home Directory</th>
<th>Login Shell</th>
</tr>
I have class Student, which looks like this:
class Student
attr_accessor :user_name, :password, :uid, :gid,
:gcos_field, :directory, :shell
attr_reader :count
def initialize(data)
#user_name,#password,#uid,#gid,#gcos_field,#directory,#shell = data
##count = defined?(##count) ? ##count += 1 : 1
end
end
There are about thirty instances of the class under the array map:
#students = datalines.map { |line| Student.new(line.chomp.split(":")) }
A sample element from datalines array is this:
dputnam:x:4185:208:Douglas Vernon Putnam:/users/dputnam:/bin/bash
I haven't been able to get the ##count to function properly either.
My failed attempt at producing a table made all the student names (of my Ruby class incidentally) display horizontally rather than vertically:
<% #students.each do |parameters| %>
<td><%= parameters.user_name %></td>
<% end %>
Any help would be appreciated!
Here's a link to the output if it helps: http://hills.ccsf.edu/~wly3/cs132a/lab4.cgi
Okay the ERB template (I think this is what it is) since it was requested:
<h1>CS132A Lab 4</h1>
<br>
<br>
<table>
<tr>
<th>Number</th>
<th>User</th>
<th>Password</th>
<th>UID</th>
<th>GID</th>
<th>GCOS</th>
<th>Home Directory</th>
<th>Login Shell</th>
</tr>
<tr>
<% #students.each do |parameters| %>
<td><%= parameters.user_name %></td>
<% end %>
</tr>
</table>
<% finish = Time.now %>
<h2>Elapsed time in seconds:<%= (finish.to_f - start.to_f).to_s %></h2>
You have to generate a new <tr> for each student:
<% #students.each do |parameters| %>
<tr>
<td><%= parameters.user_name %></td>
</tr>
<% end %>

How can I render partial in show.html.erb

I have these two models in my Ruby on Rails application - Artist and Song. They are associated as follows:
class Artist < ActiveRecord::Base
has_many :songs
attr_accessible :artist_name
and
class Song < ActiveRecord::Base
belongs_to :artist
attr_accessible :title, :track_URL, :artist_id
I have this code in views/artist/show.html.erb:
<%= render 'artist_song' %>
<table>
<% #artist.songs.each do |song| %>
<tr>
<td><%= song.title %></td>
</tr>
<% end %>
</table>
The partial Im trying to render(_artist_song.html.erb) in the same view looks like this:
<table>
<% #artist = Artist.all %>
<% #artist.each do |artist| %>
<tr>
<td><%= link_to artist.artist_name, artist %></td>
</tr>
<% end %>
</table>
The way it is suppose to work is when I click on an artist shown trough the partial, the code below the partial has to show me all the songs that belongs to the particular artist.
Both the partial and the code in the table tag are working individually. But when I put them together, it looks like there is a conflict between them and the server is showing me this No Method Error:
NoMethodError in Artists#show
Showing C:/Sites/OML/app/views/artists/show.html.erb where line #9 raised:
undefined method `songs' for #<Array:0x5fe1418>
Extracted source (around line #9):
6:
7:
8: <table>
9: <% #artist.songs.each do |song| %>
10: <tr>
11: <td><%= song.title %></td>
12: </tr>
Rails.root: C:/Sites/OML
Application Trace | Framework Trace | Full Trace
app/views/artists/show.html.erb:9:in `_app_views_artists_show_html_erb__950110288_54062208'
app/controllers/artists_controller.rb:21:in `show'
I couldn`t find a solution. Any help will be appreciated.
Thank you.
You are not using a partial. You need to render the partial inside the artist loop:
show.html.erb
<table>
<% #artists = Artist.all %>
<% #artists.each do |artist| %>
<tr>
<td><%= link_to artist.artist_name, artist %></td>
</tr>
<%= render :partial => 'artist_song', :artist => artist %>
<% end %>
</table>
This way, you are passing the current artist object to inside the partial, so there you can do:
artist_song.html.erb
<% artist.songs.each do |song| %>
<tr>
<td><%= song.title %></td>
</tr>
<% end %>

Ajax : data retrieving in rails3 + formtastic

I have successfully tried ajax saving in my sample formtastic with ajax form.
The new value is added to the database. But the the problem is in retrieving the list from the database as soon as i save via ajax.
How to do it.?
As soon as I add a new record I want my displaying list to be update. Both the option to add new record and list the data from database is in same page
This is my Index page. The controller and all other created via scaffolding
<h1>Listing samples</h1>
<table>
<tr>
<th><%=t :Name%></th>
<th></th>
<th></th>
<th></th>
</tr>
<% #samples.each do |sample| %>
<tr>
<td><%= sample.name %></td>
<td><%= link_to 'Show', sample %></td>
<td><%= link_to 'Edit', edit_sample_path(sample) %></td>
<td><%= link_to 'Destroy', sample, :method => :delete, :data => { :confirm => 'Are you sure?' } %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Sample', new_sample_path %>
<br /><br /><br /><br /><br />
<%= semantic_form_for #sample1,:url => samples_path, :remote => true do |f| %>
<%= f.inputs do %>
<%= f.input :name %>
<% end %>
<%= f.actions do %>
<%= f.action :submit, :as => :input %>
<% end %>
<% end %>
When you save via ajax, you may have to change the way your controller responds, kinda like this:
def create
# stuff
respond_to do |format|
format.js
end
end
When you do this, rails would expect you to have created a file named create.js.erb, in which you can manipulate the data of your view(append new content to your table, render a whole new partial with your new object list, etc):
$('#your_list').html(
"<%= escape_javascript(render('your_table_partial')) %>"
);
Or
$('#your_list').append(
"<%= escape_javascript(render('your_item_of_the_table_partial')) %>"
);
These are just examples, i don't know your code enough to write the correct code for you, but you sure can use these as a base for your work.
I did the CRUD operation using these guidelines and it worked perfect
http://stjhimy.com/posts/07-creating-a-100-ajax-crud-using-rails-3-and-unobtrusive-javascript

XML Parsing Error: no element found when using rjs in rails

I implemented destroy functionality using rjs template in rails. i got an error "XML Parsing Error: no element found" when destroy one record from database. is this right my coding?
I used the following versions ruby and rails:
Ruby version: 1.8.7
Rails Version: 2.3.8
Controller file:
def destroy
begin
#task = Task.find(params[:id])
#task.destroy
respond_to do |format|
#format.html { redirect_to(tasks_url) }
format.js
format.xml { head :ok }
end
rescue Exception => e
puts e
end
end
partial template file _task.html.erb:
<tr id="<%= dom_id(task) %>">
<td><%= task.name %></td>
<td><%= task.note %></td>
<td><%= task.priority %></td>
<td><%= link_to 'Show', task %></td>
<td><%= link_to 'Edit', edit_task_path(task) %></td>
<td>
<%= link_to 'Destroy', task, :confirm => 'Are you sure?', :method =>:delete,:remote => :true %>
index.rhtml file:
<div id='newform'>
<% form_for([#task, Task.new]) do |f| %>
<div>
<%= f.label 'Add a new task: ' %>
<%= f.text_field :name %>
</div>
<div>
<%= f.submit %>
</div>
<% end %>
</div>
<table id="alltasks">
<tr id="tablehead">
<th>Name</th>
<th>Note</th>
<th>Priority</th>
<th></th>
<th></th>
<th></th>
</tr>
<%= render #tasks %>
<!-- expanded: render :partial => "task", :collection => #tasks -->
</table>
<br />
<%= link_to 'New Task', new_task_path %>
destroy.js.rjs file:
page.alert('Hi')
The problem is that the xml format is getting requested from your destroy action, not the js format, and something is trying to parse the empty xml response produced by the format.xml { head :ok } line in the controller. It used to be that you could get away with the empty xml response, but it also looks like you're using unobtrusive javascript, and something somewhere in ujs tries to parse it.
One potential solution is to make a destroy.xml.builder view that produces a simple response, and change your controller action to read format.xml { render :layout => false } or something similar. You can also do some fun things with changing the data type your link is requesting, but I'd recommend avoiding that unless you really want to do something with your js response in destroy.js.rjs.

Resources