Rails String Interpolation in Model - ruby-on-rails-5

I'm trying to string interpolate in a message model.
I want to combine a string 'message' and a select media_url into a :body so I can text a text message that contains both a message and a link concatenated. Any help with the interpolation would be appreciated.
I'm trying to do a before_create to grab two fields and combine them into a 3rd field that's saved as body.
My current result yields:
MESSAGE#{#message.media_url}
message.rb
before_create do
self.body = 'MESSAGE' + '#{#message.media_url}'
end
new.html.erb
<%= f.text_field :body, :value => "body" ,:class => 'form-control ' %>
<%= f.select :media_url, Url.order('name asc').all.collect { |u| [u.name, (u.sanitized_url + u.short_url)] }, { class: 'form-control' } %>
It is suppose to output something like... Message and www.google.com/EdRds which is the value coming from the select box.
Thank you

You got the MESSAGE#{#message.media_url} result, because you're wrapping your #{} in single quotes '', that must be between double quotes.
You could try just interpolating, not concatenating:
before_create do
# Not an instance variable, the media_url attribute from the object itself
self.body = "MESSAGE #{self.media_url}"
end
Because '#{#message.media_url}' won't work as a interpolation, that must be with double quotes "", and 'MESSAGE' + is concatenating the #message.media_url value, so you could wrap all in double quotes and your variable value in {}.

Related

rails3 content_tag with static attributes

The following is being properly generated into HTML code
<%= content_tag(:span, (t 'hints.h'), :class => "has-tip", :title => (t 'hints.s') ) %>
But I am trying to generate
<span data-tooltip aria-haspopup="true" class="has-tip" title="title bla bla">translated h</span>
and have found no way to generate these span attributes data-tooltip aria-haspopup="true" They cannot be part of the options hash given one has only a name... and the second one has a dash which impedes from defining it as a symbol :aria-haspopup
I suggest that you use the following:
content_tag(:span, t('hints.h'), :class => 'has-tip', :title => t('hints.s'), :'aria-haspopup' => true, :'data-tooltip' => '')
Note that you can use the dash character in symbols if you enclose them in quotes.
The data attribute you could also specify as nested hash like :data => {:tooltip => ''} instead of :'data-tooltip' => '', use whatever you prefer.
As for the boolean attribute data-tooltip, setting the value to an empty string is as good as omitting it (and your best option with Rails 3 ;)). See also:
http://www.w3.org/html/wg/drafts/html/master/infrastructure.html#boolean-attributes

Learning to Search in Rails

I'm trying to create a search form in my rails application. I've looked up various solutions but they make little sense to me.
I'm getting the following error when I run a search through a form in my rails app. Right now my concern (other than the error) is my instance variable #computers in my index action. I'm pretty sure it's not 'the rails way' to get a search done properly and would love some advice.
Error
undefined method `%' for #<Array:0x5780460>
Parameters after Search
http://localhost:3000/computers?utf8=%E2%9C%93&direction=&sort=&search=bob
Search Form
<%= form_tag computers_path, method: "get" do %>
<%= hidden_field_tag :direction, params[:direction] %>
<%= hidden_field_tag :sort, params[:sort] %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Go", name: nil, class: "btn btn-primary" %>
<% end %>
Call to Method
def index
#computers = Computer.where(school_id: current_user.school_id).search(params[:search]).category(params[:category]).order(sort_column + " " + sort_direction)
end
Method
def Computer.search(search)
if search
search = search.downcase
params = []
values = {}
column_names.each do |c|
params << "#{c} LIKE #{c.to_sym}"
values[c.to_sym] = search
end
params.join (' OR ')
where(params,values)
else
all
end
end
You've got the right idea, but invoking the .join method does not change the object on which it is called, it merely returns a string representation. You need to store the return in a variable, something like this: paramsStr = params.join(' OR '). Then simply pass paramsStr to the where clause.
Ultimately, that is what is causing your unidentified method % for Array .... error; this version of the where method is expecting the first parameter to be a string. Check out this documentation, the part about placeholder conditions.
Hope that helps.

Concatenate field names in select

I have a form that allows you to select a facility by name then writes the id of the facility to a vale in the database.
<%= f.collection_select(:transfer_to_id, Facility.all, :id, :facility_name, {:include_blank => true}, {:class => 'select'})%>
I'd like to be able to select the facility name but to the right of the facility name display the facility_address in the form. I'm not sure how to do this, possibly an array of some sort or using a helper method.
If anyone can provide some help it would be appreciated.
Here is what ended up working properly for me by creating a Class method.
def facility_name_with_facility_address
"#{facility_name} | #{facility_address}"
end
This is untested so bear with me, but you need to add a method to your Facility model:
def facility_name_with_facility_address
facility_name << " " << facility_address
end
And then in your form you want to change the following:
<%= f.collection_select(:transfer_to_id, Facility.all, :id, :facility_name, {:include_blank => true}, {:class => 'select'})%>
To this:
<%= f.collection_select(:transfer_to_id, Facility.all, :id, :facility_name_with_facility_address, {:include_blank => true}, {:class => 'select'})%>

how to create dropdown from a hash in rails 3

In rails 3, how to create a Dropdown from hash
I have following code in my User class
class User
... other codes
key :gender, Integer # i use mongo db
class << self
def genders()
genders = {
'1' => 'Male',
'2' => 'Female',
'3' => 'Secret'
}
end
end
end
In the user form, i am trying to create a gender dropdown list
<%= f.collection_select nil, :gender, User.genders, :key, :value %>
but it complain
undefined method `merge' for :value:Symbol
So what is the proper way to create the dropdown?
Thanks
This should work:
<%= f.collection_select :gender, User.genders, :first, :last %>
Edit: Explanations:
collection_select will call each on the object you give (User.genders here) and the two methods (first and last here) on each object. It's roughly equivalent to something like this:
User.genders.each do |object|
output << "<option value=#{object.first.inspect}>#{h object.last}</option>"
end
When you call each on a Hash, it yields an Array of two values (the key and the value). These values can be retreived with the first and last methods.

Rails 3 custom validation: Highlighting offending fields

I'm writing my first custom rails validation, and would like to tag the offending class with an html "error" class if they return false - I can't quite figure out how to do it. Relevant validation code below - any help appreciated.
(If it makes a difference, I'm using jQuery)
validates_each :shop do |record, attr, value|
shopvar = record.shops.map{ |s| s.email.downcase.strip }
if shopvar.count != shopvar.uniq.count
record.errors.add(attr, 'has the same email address entered more than once')
#record.errors[attr] << "You have entered this shop in the form twice"
end
end
So in your form you'd have something like this for an input field
<%= form.text_field :title %>
Since errors is a hash you could use the "include?" method like so...
errors.include?(:title)
This tells you that there's something wrong with this field. Now all you need to do is style it.
Whack on a ternary operator asi...
<% css_class = errors.include?(:title) ? "highlight_error_class" : "no_problem_class" %>
<%= form.text_field :title, :class => css_class %>
Done.