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
Related
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.
I have a problem with my Ruby application. I created users who are associated with a resource (resource_id). The working hours of the users indicate the capacity of the resource. The resource table should display the total capacity of the resources. The total capacity of the resource results from the sum of the capacities of the users assigned to the respective resource. However, in the resource table, the same capacity is displayed for each resource (the sum of all resources).
As an an example:
I have 2 use, which each work 8 hours:
User 1: capacity 8, resource_id 1
User 1: capacity 8, resource_id 2
Now there should be 2 resources in the resource table, each with a capacity of 8. With me however both resources with a capacity of 16 ..
Here are the corresponding index files, controllers and models.
resources.index
<% provide(:title, 'Ressourcen') %>
<p id="notice"><%= notice %></p>
<h1>Ressourcen</h1>
<table id="resources" class="display">
<thead>
<tr>
<th>Name</th>
<th>Gesamtkapazität</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<% #resources.each do |resource| %>
<tr>
<td><%= resource.name %></td>
<td><%= User.sum(:capacity, :conditions => {:resource_id => resource}) %></td>
<td><%= link_to 'Anzeigen', resource %></td>
<td><%= link_to 'Entfernen', resource, method: :delete, data: { confirm: 'Sind Sie sich sicher?' } %></td>
<% end %>
</tr>
</tbody>
</table>
resource.model:
class Resource < ActiveRecord::Base
def resource_params
params.require(:resource).permit(:created_at, :name, :ocr, :cost, :oce)
end
validates :name, presence: true, uniqueness: true, length: {maximum: 50}
has_many :procedure_resources, :dependent => :destroy
has_many :procedures, through: :procedure_resources
has_many :users, :dependent => :destroy
end
resource.controller:
class ResourcesController < ApplicationController
before_action :set_resource, only: [:show, :edit, :update, :destroy]
# GET /resources
# GET /resources.json
def index
#resources = Resource.all
#procedures = Procedure.all
#project = Project.find(1)
end
def show
#resource = Resource.find(params[:id])
end
private
def set_resource
#resource = Resource.find(params[:id])
end
def resource_params
params.require(:resource).permit(:name, :oce, :oce, :cost, :ocr)
end
end
users.model:
class User < ActiveRecord::Base
belongs_to :resource
Does anyone know how I managed it, that it only shows the capacity of the respective resource in the resource.index?
The error must be in the resource.index with the following line:
<td> <% = User.sum (: capacity,: conditions => {: resource_id => resource})%> </ td>
or?
Best regards,
Phillip
I'm a new guy to ruby on rails and working on my first in-depth application. It has four tables: Questions, Options, Answers and Users. There's a list of questions and a user can vote for a unique option (stored in the Answers join table), I'm trying to get my head around table associations.
This is how I've setup my individual RB files:
class Question < ActiveRecord::Base
has_many :options
has_many :answers, :through => :options
end
class Option < ActiveRecord::Base
belongs_to :question
has_many :answers
end
class Answer < ActiveRecord::Base
belongs_to :user
belongs_to :question
belongs_to :option
end
class User < ActiveRecord::Base
has_many :answers
has_many :questions, :through => :answers
end
My questions controller is setup like this to include the options table:
#questions = Question.includes(:options).all
and the table body in my index.html.erb file:
<tbody>
<% #questions.each do |question| %>
<tr class="<%= cycle('lineOdd', 'lineEven') %>">
<td><%= question.question_text %></td>
<td><%= link_to 'Show', question %></td>
<td><%= link_to 'Edit', edit_question_path(question) %></td>
<td><%= link_to 'Destroy', question, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% question.options.each do |option_text| %>
<tr class="backgroundColor1">
<td class="optionCell"> <%= option_text.option_text %> </td>
</tr>
<% end %>
<% end %>
</tbody>
In the Question class I've used 'has_many :answers, :through => :options' - is this the correct way to go about this and how would I output the total number of votes in a table row below the associated option.
Do I need to add to or change the question controller code?
This is my first post, sorry if I'm not informative enough!
Thanks
Lets start by fixing up the relations a bit:
class Question < ActiveRecord::Base
has_many :options
has_many :answers
has_many :users, through: :answers
end
There is nothing technically wrong with has_many :answers, :through => :options but since there is a direct relation through answers.question_id we don't need to go through the options table for the relation.
Displaying the count
If we simply did:
<td class="optionCell"><%= option.answers.count %></td>
This would create a nasty n+1 query to fetch the count of the answers for each option. So what we want to do is create a counter cache which stores a tally on the options table.
Lets start by creating a migration to add the column:
rails g migration AddAnswerCounterCacheToOptions answers_count:integer
rake db:migrate
Then we tell ActiveRecord to update the tally when we create associated records, this looks a bit strange since the counter_cache: true declaration is on the belongs_to side while the column is on the other but thats just how AR works.
class Option < ActiveRecord::Base
belongs_to :question
has_many :answers
end
class Answer < ActiveRecord::Base
belongs_to :user
belongs_to :question
belongs_to :option, counter_cache: true
end
There is a little snag here. Since we may already have records we need to make sure they have correct counters. You can do this from the console but in the long run it is a good idea to create a rake task.
Option.find_each { |option| Option.reset_counters(option.id, :answers) }
This might take a bit of time since it needs to pull each Option and update the count.
Now we can display the tally like so:
<% question.options.each do |option| %>
<tr class="backgroundColor1">
<td class="optionCell"><%= option.option_text %></td>
<td class="optionCell"><%= option.answers.size %></td>
</tr>
<% end %>
.size is smart enough to use our counter cache column, but will fall back to querying the count which is a good thing for tests.
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.
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.