Rails View All records with same foreign key - mysql

Currently in my view for each customer I have this:
<p>
<b>Companyname:</b>
<%= #customer.companyname %>
</p>
<p>
<b>Licensecontact:</b>
<%= #customer.licensecontact %>
</p>
<p>
<b>Email:</b>
<%= #customer.email %>
</p>
<p>
<b>Phone:</b>
<%= #customer.phone %>
</p>
Under that i need to have a table showing all of the licenses associated with that particular customer. something like this:
<% #licenses.each do |l| %>
<tr>
<td><%= l.software.vendor %></td>
<td><%= l.software.title %></td>
<td><%= l.software.edition %></td>
<td><%= l.amount %></td>
</tr>
<% end %>
I have three tables, customers, licenses and softwares (I know they're named badly) and one license has many customers and many softwares.

You should be able to put something like this into your view:
<table>
<tr>
<th>Vendor</th>
<th>Title</th>
<th>Edition</th>
<th>Amount</th>
</tr>
<% #customer.licenses.each do |l| %>
<tr>
<td><%= l.software.vendor %></td>
<td><%= l.software.title %></td>
<td><%= l.software.edition %></td>
<td><%= l.amount %></td>
</tr>
<% end %>
</table>
From your description it's unclear how customers and licenses are linked together. One option is customer has many licenses, license belongs to one user:
class Customer < ActiveRecord::Base
has_many :licenses
# ...
end
class License < ActiveRecord::Base
belongs_to :customer
# ...
end
another option is HABTM (you've said 'one license has many customers' and 'table showing all of the licenses associated with that particular customer' which hints me to this):
class Customer < ActiveRecord::Base
has_and_belongs_to_many :licenses
# ...
end
class License < ActiveRecord::Base
has_and_belongs_to_many :customers
# ...
end

Have you done any tutorials?
Your text contradicts you: you say 'One license has many softwares', but your code says 'License l has one software, and I want to display the name, title and edition'.
Use belongs_to and has_many. On which tables I cannot tell you, because your code syas the opposite of the last line you write. But these keywords you need to lookup in the docs, to understand how they work and which migrations to make.
Then, if you made the relations in the Models, then you can just call it the way you wrote it down in your second code-part.

Related

Rails issue - undefinded method 'name'

for some reason this page wont opening using ruby on rails 5. Its giving me a undefined method `name' for nil:NilClass error.
The code was working perfectly the last time i opened it. can anyone please help? It would be very much appreciated.
here the the view page.
<h1> Your sale history page </h1>
<table class="table table-bordered table-hover table-striped">
<tr>
<th>Image</th>
<th>Title</th>
<th>Label</th>
<th>Condition</th>
<th>Customer</th>
<th>Price</th>
<th>Date Sold</th>
</tr>
<% #orders.each do |order| %>
<tr>
<td><%= image_tag order.record.image.url(:thumb)%></td>
<td><%= order.record.Title %></td>
<td><%= order.record.Label %></td>
<td><%= order.record.Condition %></td>
<td><%= order.buyer.name %></td>
<td><%= order.record.Selling_Price %> </td>
<%#THE BELOW CODE IS FOR RUBY DATE. FOUND ON rubydoc%>
<td><%= order.created_at.strftime("%-d %B, %Y") %></td>
<td>
</tr>
<%end%>
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
#the below code validates that the name present
validates :name, presence: true
#the below code tells rails that a user has many records. and that if a user is deleted so is the record
has_many :records, dependent: :destroy
has_many :sales, class_name:"Order", foreign_key: "buyer_id"
has_many :reviews, dependent: :destroy
end
class Order < ApplicationRecord
#the below validates the form fields
validates :address,:town_or_city,:state_or_county,:post_or_zip_code,:country, presence: true
belongs_to :record
# the below code tells rails that the relationship is two sided. a user can be a buyer or a seller
belongs_to :buyer, class_name:"User"
belongs_to :seller, class_name:"User"
end
Ok I guess you need quick fix put
<td><%= order.try(&:buyer).try(&:name) %></td>
this will make sure you do not get error if ther is no buyer than see witch order is without buyer
Does order table have buyer_id on all records?
Maybe, there are records where buyer_id is null.
Or order can't get buyer because there isn't matching id.
I found below link useful to know more about 'try' usage and why 'try' is better over rescue nil option in the above scenario.
https://rubyinrails.com/2015/08/27/rescue-nil-in-ruby-on-rails

Getting total count of tickets sold for a table. Rails

Okay. I'm trying to fill a table with data of how many tickets have been sold for each ticket type.
So, An event has many tickets and a ticket has a ticket_type. I need to get a total count of tickets sold for each ticket type. In the image above you can see that I'm getting the wrong data for quantity sold.
MODALS:
EVENT:
has_many :ticket_types, dependent: :destroy
has_many :purchases, dependent: :destroy
has_many :tickets, through: :purchases
TICKET:
belongs_to :ticket_type
belongs_to :purchase
TICKET_TYPE:
belongs_to :event
Here is the table loop:
<% event.ticket_types.each do |ticket_type| %>
<tr class=tickets-sold-modal__data>
<td><%= ticket_type.name %></td>
<td>$<%= ticket_type.amount.to_i %></td>
<td><%= event.ticket_type_purchases %></td>
</tr>
<% end %>
In this iteration I'm calling event.ticket_type_purchases which is this method:
def ticket_type_purchases
event.tickets.group(:ticket_type_id).count
end
That is returning the value in the screen shot for quantity sold. With the given information how can I collect the TOTAL TICKETS SOLD FOR EACH TICKET TYPE and display that on the screen?
Just change your view code to this:
<tr class=tickets-sold-modal__data>
<td><%= ticket_type.name %></td>
<td>$<%= ticket_type.amount.to_i %></td>
<td><%= event.ticket_type_purchases[ticket_type.id] || 0 %></td>
</tr>
But optimize the above code to store output of event.ticket_type_purchases in a variable, so that the database calls are not made multiple times.

Ruby on rails: How to update the view with a new query

I'm new at Ruby on Rails (I started studying this week by myself) and I'm facing some issues that I cannot solve.
I have created a project called 'projeto_ajuda' and i'm using mysql database. I access the aplication on http://localhost:3000/menu/index. It shows me a table with 5 columns, and the last one, is for a button.
What I want is: when the button is clicked, it calls a method from the controller that 'refresh' the table with a new select (i add a new condition in where statement).
Ps¹: the view show to filled rows in the table, but when I click on the button, nothing changes on the view, but the URL does: http://localhost:3000/menu/index.%23%3CMenu::ActiveRecord_Relation:0x007f5ce5891608%3E?id=6
Ps²: If I refresh_table(6) instead of refresh_table(nil) on the index method, it works just fine, selecting what I want from the database.
And if I look at the database, there is a record with the id 6.
menu_controller.rb:
class MenuController < ApplicationController
helper :all
def index
refresh_table(nil)
end
def abrir
refresh_table(params[:id])
end
private
def refresh_table(id)
if(id.nil?)
#menus = Menu.where("codigopai IS NULL")
else
#teste = Menu.find(id)
#menus = Menu.where("codigopai = '" + #teste.codigopai.to_s + #teste.codigo.to_s + "'")
end
end
end
index.html.erb:
<h1> List all </h1>
<table>
<tr>
<th>Codigo</th>
<th>CodigoPai</th>
<th>Descrição</th>
<th>Conteúdo</th>
<th></th>
</tr>
<% #menus.each do |m| %>
<tr>
<td><%= m.codigo %></td>
<td><%= m.codigopai %></td>
<td><%= m.descricao %></td>
<td><%= m.conteudo %></td>
<td><%= button_to 'Abrir', menu_index_path(#menus, :id => m.id), method: :post %></td>
</tr>
<% end %>
</table>
routes.rb:
Rails.application.routes.draw do
resources :menus
post 'menu/index'
get 'menu/index'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
Try this
menu_controller.rb
class MenuController < ApplicationController
helper :all
def index
refresh_table(params[:id])
end
private
def refresh_table(id)
if id
#teste = Menu.find(id)
#menus = Menu.where(codigopai: "#{#teste.codigopai}#{#teste.codigo}")
else
#menus = Menu.where(codigopai: nil)
end
end
end
index.html.erb
<h1> List all </h1>
<table>
<tr>
<th>Codigo</th>
<th>CodigoPai</th>
<th>Descrição</th>
<th>Conteúdo</th>
<th></th>
</tr>
<% #menus.each do |m| %>
<tr>
<td><%= m.codigo %></td>
<td><%= m.codigopai %></td>
<td><%= m.descricao %></td>
<td><%= m.conteudo %></td>
<td><%= button_to 'Abrir', menu_index_path(id: m.id), method: :post %></td>
</tr>
<% end %>
</table>
I think you can read Query with Active Record and routing

using last after model included doesnt work

Im stuck (still very new to Rails), and cant figure out why its not working:
I have:
class Message < ActiveRecord::Base
attr_accessible :updated_at
has_many :categories_messages
has_many :categories, through: :categories_messages
end
class CategoriesMessage < ActiveRecord::Base
attr_accessible :category_id, :message_id
belongs_to :category
belongs_to :message
end
class Category < ActiveRecord::Base
attr_accessible :name
has_many :categories_messages
has_many :message, through: :categories_messages
end
#messagesPer = Category.all.includes(:messages).group('categories.id').order("COUNT(messages.id) DESC")
<% #messagesPer.each_with_index do |message, i| %>
<tr>
<td><%= i+1 %></td>
<td><%= message.name %></td>
<% if message.categories_messages.exists? %>
<td><%= message.messages.last.updated_at.to_s.to_date %></td>
<td><%= message.messages.first.updated_at.to_s.to_date %></td>
<td><%= message.messages.count %></td>
<% else %>
<td>0</td>
<td>0</td>
<% end %>
</tr>
<% end %>
So i want it to show :
the name of Category, date the last message was created , date first message was created, and all messages in that category.
ALl works fine, apart from the fact that it only shows the date when the first message was created, but never the last (still shows first date on the last).
What am i doing wrong?
UPDATE:
if i put
#messagesPer = Category.all.includes(:messages).group('categories.id')
it does show the right date for last and first messages but as soon as i add order it breaks...
I might be helpful to include the error information you get after adding an order clause to the query.
However, I can spot some odd things in the code. The CategoriesMessage model seems to be there simply to satisfy the condition that a category can have many messages and vice versa. You don't need a model for this many-to-many relationship though, Rails will handle this automatically for you.
Your models should be looking like this:
class Message < ActiveRecord::Base
attr_accessible :updated_at
has_and_belongs_to_many :categories
end
class Category < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :messages
end
And in your database you have these tables: messages, categories,categories_messages, where the last one is the join table which only contains columns for amessage_idand acategory_id`.
Then you can simply do something like this in your code:
category.messages.each { |message| puts message.updated_at }
Also see this Ruby on Rails tutorial article for more information. If this doesn't work for you, please post the exact error you get.

Rails 3 with joins among 2 tables

I have 2 models, car and registrations.
class Car < ActiveRecord::Base
belongs_to :Registration
end
class Registration < ActiveRecord::Base
has_many :cars, :dependent => :destroy
accepts_nested_attributes_for :cars, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end
In CarsController:
def index
#cars = Car.all
#cars2 = Car.all(:joins => :Registration)
end
In view:
<% #cars.each do |car| %>
<tr>
<td><%= car.twitter %></td>
<td><%= car.facebook %></td>
<td>
<% #cars2.Registration.each do |h| %> #here is my problem
<%= h.email %>
<% end %>
</td>
</tr>
<% end %>
This is my statement of cars. I am trying to print for every car owner's email. The email is in table Registration (model registration). I don't know how to make a query to database, that I want to get email from table Registrations, when column registration_id in table Cars == id column of table Registrations...
So I would like to ask you, if you have a tip, how to do...
You have got your associations in capital letters. It should be in small like this
class Car < ActiveRecord::Base
belongs_to :registration
end
Also you dont have to assign 2 variables in the controller
def index
#cars = Car.includes(:registration)
end
and in the view
<% #cars.each do |car| %>
<tr>
<td><%= car.twitter %></td>
<td><%= car.facebook %></td>
<td>
<%= car.registration.email %> #here is my problem
</td>
</tr>
<% end %>
Use this instead to fetch the email:
<%= car.registration.email %>
If you want eager loading, then use the following line in your controller instead:
#cars = Car.includes(:registration)
There's no need for #cars2.