Rails / MongoDB: Variable to address object-attribute not translating - ruby-on-rails

In my class AleShot I have some dynamic mongoid-attributes. In order to index them, I collect all attributes in an array called "dynamos". Now when I want to list these (see code below) I get: undefined method 'dyn_f' for #<AleShot:0x007f8f7ab18328>
Any Ideas why the dyn_f-variable isn't translated correctly?
<% #ale_shots.each do |ale_shot| %>
<tr>
<td><%= ale_shot.name %></td>
<% dynamos.each do |dyn_f| %>
<td><%= ale_shot.dyn_f %></td>
<% end %>
</tr>
<% end %>

That could be because dyn_f is not defined as a field in the model.
Access it like this
ale_shot['dyn_f']

Related

Removing conditional logic from a shared partial view or alternative solution

For a current project, I have duplicate code between views, and I'm not sure of the best route to refactor it.
I appear to be in a position where I can have duplicate code across various .html.erb files, or I could put identical code into a partial and use conditionals. I've always heard logic should stay out of views. Neither option seems ideal, and I don't currently know of alternatives.
To illustrate my question, I created a simple rails app called animals. I scaffolded for two models: one for cat and one for dog. Images display their corresponding attributes:
Displaying #cats and #dogs is pretty much the same. Cats just have a column for meows while Dogs have a column for barks, and a dog has the additional attribute column of plays_catch.
Lets say we choose to reduce the duplicate code for displaying cats and dogs by making a shared view partial:
#views/shared/_animal.html.erb
<tr>
<td><%= animal.name %></td>
<td><%= animal.age %> </td>
<% if animal.class == Cat %>
<td><%= animal.meows %> </td>
<% end %>
<% if animal.class == Dog %>
<td><%= animal.barks %> </td>
<td><%= animal.plays_catch %> </td>
<% end %>
</tr>
Then to render #cats = Cat.all:
<%= render partial: "shared/animal", collection: #cats %>
Then to render #dogs = Dog.all:
<%= render partial: "shared/animal", collection: #dogs %>
Obviously it would be overkill to do something like this for this specific example, but the real world project I'm applying it to would not be overkill.
The overall question is: how do you remove nearly identical code that iterates over collections, where the only difference is adding/removing a column of information? It just doesn't feel right to put that logic in the view itself, and leaving the duplication feels wrong.
You could use decorators and add methods that return the extra column(s):
class DogDecorator < Draper::Decorator
def extra_columns
[:barks, plays_catch]
end
end
class CatDecorator < Draper::Decorator
def extra_columns
[:meows]
end
end
...
<% animal.extra_columns.each do |column| %>
<td><%= animal.attributes[column.to_s] %>
<% end %>
...
<% #cats = CatDecorator.decorate_collection(Cat.all)
<%= render partial: "shared/animal", collection: #cats %>
You can use respond_to? to solve the problem more generically. The view logic doesn't feel so wrong when it's more generic.
<% [:meows, :barks, :plays_catch].each do |method| %>
<% if animal.respond_to?(method) %>
<td><%= animal.send(method) %> </td>
<% end %>
<% end %>
You can add a method of the same name to both Cat and Dog classes which would return the specific instance attributes names and values. I'd recommend returning two arrays (one with the names of the fields, other with the fields' values, or vice-versa) since hashes are not exactly ordered. This way you can control the order in which they'll appear in the view.
For example:
#models/cat.rb
def fields_and_attributes
fields = ["Name","Age","Meows"]
attributes = [self.name, self.age]
if self.meows
attributes.push("Yes")
else
attributes.push("No")
end
[fields,attributes] # make sure each attribute is positioned in the same index of its corresponding field
end
#models/dog.rb
def fields_and_attributes
fields = ["Name","Age","Plays catch"]
attributes = [self.name, self.age]
if self.plays_catch
attributes.push("Yes")
else
attributes.push("No")
end
[fields,attributes] # make sure each attribute is positioned in the same index of its corresponding field
end
#controllers/animals_controller.rb
def display_animals
#animals = Cat.all + Dog.all # an array containing the different animals
end
#views/display_animals.html.erb
for i in (0...#animals.size)
fields_and_attributes = #animals[i].fields_and_attributes
for f in (0...fields_and_attributes[0].size)
<p><%= fields_and_attributes[0][f] %> : <%= fields_and_attributes[1][f] %></p>
end
end
Here, we first iterate over all of the animals and call the .fields_and_attributes method of that specific record; we then iterate over the results of calling that method, displaying fields and attributes in the same order as the one defined within the method and also guaranteeing that the code will display every field and every attribute regardless of the difference in the total number of fields for each different animal.
I don't know of any canonical way to accomplish this, but I would use one partial for this in the following way:
<tr>
<% animal.attributes.each do |_, value| %>
<td><%= value %></td>
<% end %>
</tr>
You can get rid of repeated attributes calls by providing in the partial a local variable with pre-obtained model attributes.
EDIT: if you only want to display some attributes.
# Declare whitelist of attributes
# (you can also declare a blacklist and just calculate the difference between two array: all_attributes - blacklist_attributes):
<% whitelist = [:name, :age, :barks] %>
<%= render partial: 'shared/animal',
collection: #dogs,
locals: {attrs: (#dogs.first.attributes.keys.map(&:to_sym) & whitelist)} %>
views/shared/_animal.html.erb:
<tr>
<% attrs.each do |attr| %>
<td><%= animal[attr] %></td>
<% end %>
</tr>
Below is my answer after reviewing posted answers. Basically:
I left the differences within each scaffold model's index page
I made shared partials for common table headers and table data
code below:
#app/views/cats/index.html.erb
<h1>Listing Cats</h1>
<table>
<thead>
<tr>
<%= render partial: "shared/cat_dog_table_headers" %>
<th>Meows</th>
</tr>
</thead>
<tbody>
<% #cats.each do |cat| %>
<tr>
<%= render partial: "shared/cat_dog_table_data", locals: {animal: cat} %>
<td><%= cat.meows %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Cat', new_cat_path %>
And for the dogs:
#app/views/dogs/index.html.erb
<h1>Listing Dogs</h1>
<table>
<thead>
<tr>
<%= render partial: "shared/cat_dog_table_headers" %>
<th>Barks</th>
<th>Plays catch</th>
</tr>
</thead>
<tbody>
<% #dogs.each do |dog| %>
<tr>
<%= render partial: "shared/cat_dog_table_data", locals: {animal: dog} %>
<td><%= dog.barks %></td>
<td><%= dog.plays_catch %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Dog', new_dog_path %>
The shared table headers for cats and dogs:
#app/views/shared/_cat_dog_table_headers
<td><%= Name %></td>
<td><%= Age %></td>
The shared table data for cats and dogs:
#app/views/shared/_cat_dog_table_data_headers
<td><%= animal.name %></td>
<td><%= animal.age %></td>

Show attribute value using its id

In my application, I am grouping my objects by an ID. At the moment, I can only display the ID, but I would like to display the attribute value.
A Fixture belongs_to a tournament and a tournament has_many fixtures.
Controller
def index
#fixtures = Fixture.all
#tournament_fixture = #fixtures.group_by {|f| f.tournament_id}
end
View
<% #tournament_fixture.sort.each do |tourn_name, fixture| %>
<%= tourn_name %>
<% fixture.each do |f| %>
<td><%= f.home_team %></td>
<td><%= f.away_team %></td>
<td><%= f.kickoff_time %></td>
</tr>
<% end %>
<% end %>
How can I get
<%= tourn_name %>
to display its corresponding value that is in its :name column?
At the moment in my view for example i get this returned
<tbody>
2
<tr>
<td>Tournament Name</td>
<td>Team 1</td>
<td>Team 2</td>
<td>2000-01-01 14:00:00 UTC</td>
<td><a class="btn btn-success" href="/fixtures/1">view</a></td>
</tr>
</tbody>
The 2 needs to be the value in the :name column
I'd recommend grouping by tournament instead:
#tournament_fixture = #fixtures.group_by(&:tournament)
And then iterate using:
<% #tournament_fixture.sort.each do |tournament, fixture| %>
<%= tournament.name %>
...
<% end %>
You can access the whole object much like you can get the id like this:
def index
#fixtures = Fixture.includes(:tournaments).all
#tournament_fixture = #fixtures.group_by {|f| f.tournament.name}
end
The id is still available as either f.tournament_id or f.tournament.id, should you still need it but I just figured you'd rather group by its name directly. I simply added an includes statement to also load the referenced Tournament objects with your fixtures in one go. Otherwise, Rails would load the tournaments only when you access them one by one.
As an alternative, you could load the Tournaments, including all their the fixtures instead and iterate over the tournaments like this:
Controller
def index
#tournaments = Tournament.includes(:fixtures).all
end
View
<% #tournaments.each do |tournament| %>
<%= tournament.name %>
<% tournament.fixtures.each do |f| %>
<td><%= f.home_team %></td>
<td><%= f.away_team %></td>
<td><%= f.kickoff_time %></td>
</tr>
<% end %>
<% end %>
It seems a bit more natural to me and you don't need to iterate over all fixtures to map them by their tournament.
You can load the fixtures in the right order. There is no need to group then in memory. Remember to include the tournaments to avoid N+1 queries.
# controller
def index
#fixtures = Fixture.order(:tournament_id).includes(:tournaments).all
end
Loading in the right order in the controller makes the view simpler. For the tournament's name just use the association between Fixture and Tournament.
# view
<% #fixtures.each do |fixture| %>
<tr>
<td><%= fixture.tournament.name %></td>
<td><%= fixture.home_team %></td>
<td><%= fixture.away_team %></td>
<td><%= fixture.kickoff_time %></td>
</tr>
<% end %>

undefined method `ncbi_ref_seq' for #<ActiveRecord::Associations::CollectionProxy []>

Generator has_many:results
Result belongs_to:generator
I want to have a page whereby i can view all the generators and the results.
For example :This is from my generator/index.html
this is from result/index.html
what i want to have is to combine them together and view all the data.
right now this is what i've changed but i get the error message undefined method for ncbi_ref_seq. ( ncbi_ref_seq is an attribute belonging to the class Result )
GeneratorController.rb
def index
#generators = Generator.all(:include => [:results])
end
Generator/index.html.erb
<tbody>
<% #generators.each do |generator| %>
<tr>
<td><%= generator.primer_length %></td>
<td><%= generator.choice %></td>
<td><%= generator.random_primer_generated %></td>
<td><%= generator.c_primer %></td>
<td><%= generator.results.ncbi_ref_seq %></td>
</tr>
<% end %>
Since a generator has many results. When you take generator.results it returns an Active Record Collection, so there would be several records of Results, so you can't just extra a ncbi_ref_seq.
Either you have to loop through generator.results and output each ncbi_ref_seq like so
<% for result in generator.results %>
<%= result.ncbi_ref_seq %>
<% end %>
Or a generator has_one result.

Rails undefined method `hospital' for nil:NilClass

Respected ppl ...
In my application i want to display the last hospital name for a given employee ...
for which i tried this :
<%= #employee.postings.last.hospital.hospital_name %>
All the required associations are correct ...as this works perfectly for all the employees who have a posting ... but i get the error for the employees who dont have even a single posting ...
I tried doing
<%= #employee.postings.last.hospital.hospital_name.to_s %>
and even
<% if !#employee.postings.last.hospital.nil? %>
and even a "try" function ....
I just want it to not display any data when there dosent exist one ... instead of the intimidating error ...
if i could just learn how to skip over printing nil values then it would be awesome ..as i am facing similar issues elsewhere too ...
For ex :
in my employees main page i want to display all the qualifications for each employee for which im doing :
<tbody>
<% #employees.each do |employee| %>
<tr>
<td><%= employee.emp_id %></td>
<td><%= employee.emp_treasury_id %></td>
<td><%= link_to employee.emp_full_name,employee_path(employee) %></td>
<% #employee.qualifications.each do |qualification| %>
<td><%= qualification.qualification_name.Qualification_name %></td>
<% end %>
</tr>
<% end %>
but i end up getting "undefined method `qualifications' for nil:NilClass" error once again ...
Im trying a lot ... but still ...
Thanx and Sincere Regards
-Sky
Try this
<%= #employee.postings.last.try(:hospital).try(:hospital_name) || "N/A" %>
using try
<%= #employee.postings.last.try(:hospital).try(:hospital_name) %>
using if
<%= #employee.postings.last.hospital.hospital_name if #employee.postings.exists? && #employee.positings.last.hospital %>
It should be
employee not #employee
Rest you use try or respond_to for being more safe. As you might not have run the migrations.
.respond_to?(:field) && model.try(:field)
Thanks
<% #employees.each do |employee| %>
<tr>
<td><%= employee.emp_id %></td>
<td><%= employee.emp_treasury_id %></td>
<td><%= link_to employee.emp_full_name,employee_path(employee) %></td>
<% employee.qualifications.each do |qualification| %>
<td><%= qualification.try(:qualification_name).try(:Qualification_name) %></td>
<% end %>
</tr>
<% end %>

Rails - how do you access a foreign key object in a html.erb template? Works in console

I am learning rails by trying to model a collectible card game.
I have a champion model and a rarity model. I have the has_many/belongs_to in the model definition and this works in the console:
c = Champion.find(1)
c.rarity.name
=> "Uncommon"
When I do the same thing in a template, I get
<%= champion.rarity.name %>
undefined method `name' for nil:NilClass
Any ideas on how to get this to work?
This is on Rails 3.2.2.
Update: Full .erb code
<% #champions.each do |champion| %>
<tr>
<td><%= champion.name %></td>
<td><%= champion.rarity.name %></td>
</tr>
<% end %>
If every Champion does not have a Rarity association (some are nil), you can use a .try() to print the name. Otherwise the .each will fail with a NoMethod when one without a Rarity is encountered.
<% #champions.each do |champion| %>
<tr>
<td><%= h champion.name %></td>
<td><%= h champion.rarity.try(:name) %></td>
</tr>
<% end %>
Or the less clever unless nil method:
<% #champions.each do |champion| %>
<tr>
<td><%= h champion.name %></td>
<td><%= h champion.rarity.name unless champion.rarity.nil? %></td>
</tr>
<% end %>
Note: I have also added the h() helper method to encode these for HTML output, though this is done automatically in Rails 3.

Resources