How to sort this by count of events?
I tried diffrences ways but it still doesn't work:
<tr>
<% User.all.each do |user| %>
<td> <%= user.name %></td>
<td> <%= user.events.count %></br></td>
<% end %>
</tr>
And this is a model:
class User < ActiveRecord::Base
has_many :events
Thanks for answers.
You can achieve it through counter_cache
class Event < ActiveRecord::Base
belongs_to :user, dependent: :destroy,counter_cache: true
end
Add a column events_count to your users table like this
add_column :users, :events_count, :integer, :default => 0
and use it in the view like this
<tr>
<% User.all.each do |user| %>
<td> <%= user.name %></td>
<td> <%= user.events_count %></br></td> #here
<% end %>
</tr>
I would like to suggest to look into this Railscasts,but it is old.
Look in to this plugin And here is an example how it is done.
Hope it helps.
Related
I am having a problem in the eyes when presenting the data.
I have 3 user models, sponsors and pets Result that sponsors in a table join between users and pets that are nan, my problem is in the hour to show all the sponsors of the mascot in sight and achievement but in a wrong way to La time to msotrar the data. I hope you can tell me how to fix it. Thank you.
Index.html.erb
<h1>Sponsors#index</h1>
<table class="table table-bordered table-hover table-striped" id="histories">
<thead>
<tr>
<th>Mascota</th>
<th>Padrinos</th>
<th>Apadrinar</th>
</tr>
</thead>
<tbody>
<% #pets.each do |pet| %>
<tr>
<td><%= pet.name %></td>
<td>
<% #users.each do |user| %>
<% #sponsors.each do |sponsor| %>
<% if user.id == sponsor.user_id and pet.id == sponsor.pet_id %>
<%= user.email%>
<% else %>
<p>No Tengo Padinos =-( </p>
<% end %>
<% end %>
<% end %>
</td>
<td><button>Apadrinar</button></td>
</tr>
<% end %>
</tbody>
</table>
My controller has the three models that I am sending to view.
def index
#sponsors = Sponsor.all
#users = User.all
#pets = Pet.all
end
pet.rb
class Pet < ApplicationRecord
has_many :adoptions
belongs_to :race, required: false
has_many :users, through: :sponsors
end
user.rb
class User < ApplicationRecord
has_many :pets, through: :sponsors
end
sponsor.rb
class Sponsor < ApplicationRecord
belongs_to :user
belongs_to :pet
end
The output that now shows me the attachment in the image.enter image description here
I also wonder if there is a better way to make the query, to show the respective data.
Another thing is how would I do to no longer be able to sponsor pets that I have already given a sponsor?
You are using a through table to join users and pets, but your associations aren't setup properly. For a through model, you have to have_many of the through table along with a has_many: :through association. Your associations should look like this:
class Pet < ApplicationRecord
has_many :adoptions
belongs_to :race, required: false
**has_many :sponsors**
has_many :users, through: :sponsors
end
class User < ApplicationRecord
**has_many :sponsors**
has_many :pets, through: :sponsors
end
Afther working and following diferent recomendations here is my solution.
<% #pets.each do |pet| %>
<tr>
<td> <%= pet.name %></td>
<td>
<% if pet.sponsors.any? %>
<% pet.sponsors.each do |sponsor| %>
| <%= sponsor.user_email %> |
<% end %>
<% else %>
<p>No Tengo Padinos =-( </p>
<% end %>
</td>
<td>
<%= link_to "Apadrinar", {:controller => "sponsors", :action => "new", :mascot => pet.id }%>
</td>
</tr>
<% end %>
I changed also my models.
sponsor.rb
class Sponsor < ApplicationRecord
belongs_to :user
belongs_to :pet
has_many :gifts
delegate :email, to: :user, prefix: true, allow_nil: true
end
user.rb
class User < ApplicationRecord
has_many :sponsors
has_many :pets, through: :sponsors
end
pet.rb
class Pet < ApplicationRecord
has_many :sponsors
has_many :users, through: :sponsors
end
And finally mi index on Controller.
sponsors_controller.rb
def index
# #sponsors = Sponsor.all
# #users = User.all
# #pets = Pet.all
# #pets_no_sponsors = Pet.where.not(id: Sponsor.select("pet_id")).select("id")
#pets = Pet.includes(:sponsors)
end
By making a delegation now I only make a query which sends everything necessary to my index.
Frnds I am new to rails, here i created two tables caleed stocks and stock_availabilities.
in the stock model
class Stock < ActiveRecord::Base
belongs_to :projects_lkp
has_many :stock_availabilities
validates_presence_of :item
end
In the stock_availabilities model
class StockAvailability < ActiveRecord::Base
belongs_to :stock
validates_presence_of :qty,:add_or_issue,:price, :captured_at, :stock_id,:unit
end
Now my doubt is how to bring the field of stock_availabilties in the views of stock
<% #stock.each do |d| %>
<tr>
<td><%= d.item %></td>
"Here i need to print the values of qty and pricevwhich is in stock_availabilities class"?
</tr>
You are on the right track.
this is what you need:
<% #stock.each do |d| %>
<tr>
<td><%= d.item %></td>
<% d.stock_availabilities.each do |sAV| %>
<td> <%= sAV.qty %> </td>
... <-- You do the other ones here
<% end %>
</tr>
I'm trying to reference a column from another table in my rails application. I want to reference the site_name using the matching site_id columns from both tables(sites and trials).
My controller
def list
#list = Trial.year(params[:year]).order(:region_id)
end
My Models
class Trial < ActiveRecord::Base
attr_accessible :trial_id, :site_id, :year, :trial_type, :region_id
scope :year, ->(year) { where(year: year) }
scope :trial_id, ->(trial_id) { where(trial_id: trial_id) }
belongs_to :site
end
class Site < ActiveRecord::Base
attr_accessible :site_id, :site_name, :region
has_many :trials
end
My View
<table class="table">
<th>Trial Location</th>
<th>Trial Type</th>
<th>Grower</th>
<% #list.each do |list| %>
<tr>
<td>
<%= link_to list.site.site_name, trial_trials_path(trial_id: list.trial_id) %>
</td>
<td>
<%= link_to list.trial_type, trial_trials_path(trial_id: list.trial_id) unless list.trial_type.blank? %>
</td>
<td>
<%= link_to list.trial_type, trial_trials_path(trial_id: list.trial_id) unless list.trial_type.blank? %>
</td>
</tr>
<% end %>
</table>
Setting up the association in your model does write the getter method for you. The attr_accessibles sets up that method.
Add :site to your Trial's attr_accessible
I have these three models.
Student.
Evaluation.
Grade (student_id, evaluatioin_id, value)
I want to make a form so that a User can set the grade for each student of a evaluation...
I want to keep this is as clean as possible (and restful)...
Im open to any suggestions on how to get this done.
Please Help.
See these
http://railscasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2
I suppose you have the following associations:
Evaluation:
class Evaluation < ActiveRecord:Base
has_many :grades
accepts_nested_attributes_for :grades
end
Student:
class Student < ActiveRecord::Base
has_many :grades
end
Grade:
class Grade < ActiveRecord::Base
belongs_to :student
blongs_to :evaluation
end
Regarding your comment I think you want to use the nested_form_for gem made by Ryan Bates. It helps you add/delete dynamically nested attributes in your form, very efficiently. You can use it like this:
<% nested_form_for #evaluation do |f| %>
<% f.fields_for :grades do |gf| %>
<%= gf.label 'Username of the student' %>
<%= gf.collection_select(:student, :student_id, Student.All, :id, :username) %> <br/>
<%= gf.label :value %>
<%= gf.text_field :value %> <br/>
<%= gf.link_to_remove 'delete' %> <br/>
<% end %>
<%= f.link_to_add 'Add grade', :grades %> <br/>
<%= f.submit %>
<% end %>
Tell me if it works/fits your needs. I have been using this gem a lot these previous days.
What I ended up doing was..
In Grade Model
scope :for_student,lambda{|student, evaluation| where("student_id"=>student.id).where("evaluation_id"=>evaluation.id)}
In EvaluationsController
def assign_grades])
#evaluation = Evaluation.find(params[:id])
#students = Student.all
#students.each do |s|
grade = Grade.for_student(s,#evaluation)
if !grade.exists?
#evaluation.grades.build(:value=> 0,:student_id=>s.id)
end
end
end
def save_grades
#evaluation = Evaluation.find(params[:id])
#evaluation.update_attributes(params[:evaluation])
redirect_to [#evaluation.batch_subject, #evaluation]
end
In View
<table class="medium">
<thead>
<tr>
<th>name</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<%=f.fields_for :grades do |g|%>
<tr>
<td><%=g.label :value,g.object.student.full_name%> <%= g.hidden_field :student_id%></td>
<td><%=g.text_field :value%></td>
</tr>
<%end%>
</tbody>
</table>
My goal is to display select box for each relation for users and specific project.
All users need to be listed but only project users have some type of relation. Other users have none selected in theirs select box.
I have this model:
class Project < ActiveRecord::Base
belongs_to :company
has_many :tasks, :order => 'state_type_id ASC'
has_many :project_user_relations
has_many :users, :through => :project_user_relations
def t_name
name.camelcase
end
end
class User < ActiveRecord::Base
belongs_to :company
has_many :tasks , :foreign_key => :assigned_user_id
has_many :project_user_relations
has_many :projects, :through => :project_user_relations
def full_name
firstname + ' ' + lastname
end
def relation_to(project)
relation=ProjectUserRelation.find_by_project_id_and_user_id(project.id, id)
relation ||= relation=ProjectUserRelation.new
end
end
class ProjectUserRelation < ActiveRecord::Base
belongs_to :project
belongs_to :user
has_one :project_user_relation_type
end
class ProjectUserRelationType < ActiveRecord::Base
def t_name
I18n.t("app.projects.users.relation.type."+code)
end
end
I want make a form to display all users, with collection_select.
I used code:
def edit_all
#project = Project.find(params[:project_id])
#users = User.all
....
in my controler
routes works ok.
in my view:
<% #users.each do |user| %>
<%= f.fields_for :users, user do |user_fields| %>
<tr class="reference" rel="<%= parent_user_path(user) %>" >
<td class="name"><%= link_to user.full_name, parent_user_path(user) %></td>
<td class="email"><%= mail_to user.email %></td>
<td class="type">
<%= user_fields.fields_for user.relation_to #project do |relation_fields| %>
<%= relation_fields.collection_select :project_user_relation_type, ProjectUserRelationType.all, :id, :t_name, {:include_blank => false, :prompt => t("helpers.select.prompt") } %>
<% end %>
</td>
</tr>
<% end %>
<% end %>
or for test:
<%= f.fields_for :users, #users do |xuser_fields| %>
<% logger.debug "#{self.to_s} xuser_fields = #{xuser_fields.object.inspect} ;" %>
<tr>
<td><%= xuser_fields.text_field :firstname %></td>
<td></td>
<td></td>
<td></td>
</tr>
<% end %>
but notnihng woks right
first one generates wrong name in html:
select id="project_users_project_user_relation_project_user_relation_type" name="project[users][project_user_relation][project_user_relation_type]"
second one generates error:
undefined method `firstname' for # Array:0x4d03658
Can you help me to solve this situation.
PS:sorry for long code :(
SOLUTION (probably - solved by reading RoR sources)
I found sollution i thing.
A method
def name_attributes=(attributes)
# Process the attributes hash
end
in Project model was missing.
It is unbelievable sollution :].
There is also exact syntax after fields_for: :name, #some_collection, where name must be exactly same name as in the beginign of mentioned def in Model.