Setting page titles as attribute values with Rails - ruby-on-rails

I'm wondering if anyone knows to how to set a page's title to an attribute.
Was thinking something along the lines of:
<% content_for :title, "Museum | '#gallery.name'" %>
But I cant figure out what to wrap #gallery.name in, if this is even the right approach.
It's probably a really simple question, but I seem to be stumped!

maybe?
<% content_for :title do %>
(#gallery && #gallery.name) || 'Museum'
<% end %>
of course yield :title somwewhere is required
credits to #Clark
if the text should be Museum | foobar if #gallery name exists then instead of
(#gallery && #gallery.name) || 'Museum' it should be
"Museum | #{#gallery && #gallery.name} (in case #gallery is always guaranteed to be defined even simplier "Museum | #{#gallery.name}" (remember to use double " not ').

Related

How do I elegantly check for presence of both the object and associated objects?

I have an instance variable #tally_property, and if there are photos on that object I would like to cycle through the photos and show them.
So my code snippet looks like this:
<% if #tally_property.photos.present? %>
<% #tally_property.photos.each_with_index do |photo, index| %>
The issue is that based on the above, if #tally_property is nil, then the entire first line throws an error.
So is there a 'nil' check I can do that isn't bulky, i.e. I don't want to do if #tally_property.nil?, on both the primary object and the association, and is elegant and ruby & rails-esque?
I would use the safe navigation operator (&.) and write something like this:
<% #tally_property&.photos&.each_with_index do |photo, index| %>
...
<% end %>
In Ruby 2.3.0+ you can use the safe navigation operator:
#tally_property&.photos
ActiveSupport has a .try method that can be used to the same end in older versions of ruby:
#tally_property.try(:photos)
You can add a simple conditional to be able to safely iterate through the collection:
<% (#tally_property.try(:photos)||[]).each_with_index do |photo, index| %>
<% end %>
Rails 4 adds ActiveRecord::Relation#none and a change in behaviour so that associations always return a ActiveRecord::Relation. So its perfectly acceptable to write:
<% #tally_property.try(:photos).try(:each_with_index) do |photo, index| %>
<% end %>
After upgrading your app. Or you can use a partial and render:
<%= render partial: 'photos', collection: #tally_property.photos if #tally_property %>
Which removes the need for writing the iteration.
Use && (or and, they each have their sweetspot).
Taking it out of Erb for a moment, I would generally write something like this:
if #tally_property and #tally_property.photos.present?
Depending on photos I might use:
if #tally_property and #tally_property.photos
or perhaps:
if #tally_property and not #tally_property.photos.empty?
Sometimes I'll use a temporary variable:
if (photos = #tally_property && #tally_property.photos)
photos.each #…
That kind of thing.
I would recommend this episode of Ruby Tapas, And/Or for a longer (but still quick) look at it.
One more way, just select all photos connected to this tally_property:
example how it might be:
Photo.joins(:tally_property).each_with_index do |photo, index|

How to sort a list containing a string alphabetically in rails view - rails 4

i am new to rails and any help would be much appreciated.
i am trying to sort my list by status, but i have string in code stating "Pending"
i believe the error is prompting up because it can not place the status in order because i have a string
could one kindly advise the best way to go about sorting out a list in alphabetical order where by the list contains a string - thank you
error message
comparison of String with nil failed
jobseekerpg.html.erb
<% #userj_applications.sort_by(&:status).each do |application| %>
<%= link_to application.advert.title, userr_advert_path(application.advert.userr, application.advert) %> |
<%= application.advert.city %> |
<%= application.advert.category_country.name %> |
<span>
status:
<% if application.status == nil %>
<%= "Pending" %>
<% else %>
<%= application.status %>
<% end %>
</span> |
applied: <%= application.created_at.strftime("%B %d, %Y") %><br>
<% end %>
static_controller.rb
class StaticPagesController < ApplicationController
respond_to :html, :xml, :json
def jobseekerpg
#userj = Userj.find(current_userj)
#userj_applications = #userj.forms
end
end
my suggestion:
i currently have a column named status in my table
do i create another column in my table called statusPending
make this as a hidden_field and assign it to pending statusPending:Pending
so whenever an application status is nill i can use an if & else statement to call up application.statusPending
but then i will not need to only sort by status , i will need to sort by status & statusPending
any advise or help will be much appreciated
could one kindly advise the best way to go about sorting out a list in
alphabetical order where by the list contains a string - thank you
Array#sort
stringList.sort!
The "array.sort!" should sort the list in-line.
Here are some ruby examples with blocks http://www.dotnetperls.com/sort-ruby
Looks like you are getting that error when the sort_by method tries to compare a non null status with a null one. You could try to replace your statement:
#userj_applications.sort_by(&:status).each do |application|
with
#userj_applications.sort {|x,y| (x.status || '') <=> (y.status || '') }.each do |application|
This way nil values are treated as empty strings during sort.

Building a selectbox or filter in Rails

Hi maybe this is a fool question, but i really try to look couldnt find any relevant info, (maybe cause i dont know where exactly to start looking at) ..
I need to build a select box with options so the user can "filter" by the candidate.poisition value i have. at this moment the view has this code..
I was thingin on using :params, to post them in URL (i have always do php, im doing rails cause my task now is to insert a design, i achieve everything, just missing a selectbox filter)
Anyway.. here is the code.. wich is pretty simple
<% #candidates.each do |candidate| %>
<% if (candidate.active == true) && (candidate.position.present?) %>
All the html code with info.. like
<%= candidate.name %> : <%= candidate.position? ? t('generales.'+candidate.position) : t('activerecord.models.elite') %>
<% end %>
<% end %>
how can i make this , as im really a noob in Rails, im a regular user on PHP not even really good jaja, pls, i hope someone can give me a hand on this.
Can I use something like this : How to do a LIKE query in Arel and Rails?
Like candidates.where("position like '%?%'", params[:query]).to_sql
Also how can i build the Post as you do in PHP , no idea, to change the position that you want to filter.
Model Candidate.rb just have this inside :S
class Candidate < ActiveRecord::Base
end
Basically you're right. Here is improved code:
<% #candidates.each do |candidate| %>
<% if candidate.active && candidate.position.present? %>
<%= candidate.name %> : <%= t("generales.#{candidate.position}") %>
<% end %>
<% end %>
Update per request in comments:
Use code like this in controller:
if params[:position] == 'red'
#candidates = #candidates.where(position: 'red')
elsif params[:position] == 'blue'
#candidates = #candidates.where(position: 'blue')
else
#candidates = Candidate.all
end
and build html form that will pass parameter position.
or you can use https://github.com/activerecord-hackery/ransack

Rails: display #cars as a comma-separated list

Based on this query:
#cars = Car.where("manufacturer_id IN ?", #mfts.select("id")).limit(30).select("id")
How can I display the cars' IDs in the view like this (or do I need to rewrite my query)?
3,2,5,12,15,24,34,63,64,65,66,85
Thanks a lot - I've looked for this but couldn't find the right question/answer.
One solution is to do:
#view
<% #cars.each do |c| %><%= c.id %>,<% end %>
I don't know if there's a better way to go about it - this obviously leaves a stray comma at the end of the list (which isn't a dealbreaker). Any more elegant solutions?
One line:
<%= #cars.map(&:id).join(",") %>
If writing &:id seems confusing, there's another way that's a little more readable.. If y'all want to access a method or attribute, it might look better to inline a block.
<%= #cars.map { |car| car.id }.join(", ") %>
P.S... another name for map is collect.. that's what it's called in Smalltalk.
Lookin' good!
With Rails 3.0+ you can now write:
<%= #cars.map { |car| car.id }.to_sentence %>
Rails will appropriately add the comments and the word 'and' between the last two elements.

A blank? version for database fields which has 0 oder NULL?

in my database I have a field which holds foreign keys. Sometimes the values are NULL or 0.
I know the helper blank?. Is there something similar to enable if there is a number set in the field? Because blank doesn't work here.
the code for the view is something like this
<%= #b.author unless #b.author_id.blank? %>
you could write your own helper
def identified? author
author.id.blank? or author.id == 0
end
You could try something like:
<% if #b.author_id == 0 %>
#display something here
<% else %>
#display something else
<% end %>
in your view.

Resources