I have been working on a side project and I'm kind of stuck here
So I extract some info in the form of an array using
<%= #link.pixels.select{|x| x['platform']=='Facebook'} %>
Where the result is
[#<Pixel id: 1, platform: "Facebook", name: "Facebook", pixel: "189874014884804", created_at: "2017-10-17 18:44:13", updated_at: "2017-10-17 18:44:13">]
How can I extract the value of pixel from this array?
Also, is this the correct approach to select? What if there are two duplicate entries in Pixel with the platform name "Facebook"?
I have been stuck at this for while now.
If what you are trying to do is display the value of the pixel attribute from a collection of Pixel instances where the platform matches the string "Facebook" this is what you'd do:
<% #links.pixels.each do |pixel| %>
<% if pixel.platform == 'Facebook' %>
Pixel: <%= pixel.pixel %>
<%end%>
<%end%>
Related
I'm having some weird problems with rails params. I have two models: Page and NewsItem.
Page: has_many :news_items
and
NewsItem: belongs_to :page
In my form for creating new news_item I have a list of radio buttons with which I can select a page to which newly created item will belong.
Everything is working correctly so far. What is bugging me is:
When I select first option (page has no parent -> value passed should be nil) the value actually passed in parameters for page_id is "on"!
So I have few questions:
Since I need to do some checking of the value of params for proper redirecting, I'm wondering can I count on page_id using value "on" to represent nil? Is this a standard way in rails to represent nil or is this specific to my setup? Is there a chance that this will change in future versions?
As you can see in hash from console on the bottom of the post, after selecting nil as a value to pass as foreign key (page_id), the value actually set as page_id is not nil but 0. Is this a good way of stating that this item does not belong to a page, or should I try to force the value to be nil? Should I be passing a value of zero instead of nil?
Is there a chance for a table to have a row with primary id of zero?
I'm running this in development, on rails 4.0.4 with sqlite
Here is the part of the form with radio buttons:
<ul>
<li>
<%= f.radio_button :page_id, nil %>
<%= f.label :page_id, t('page_no_parent'), value: nil %>
</li>
<% #parents.each do |page| %>
<li>
<%= f.radio_button :page_id, page.id %>
<%= f.label :page_id, page.name, value: page.id %>
</li>
<% end %>
</ul>
Here is the actual params hash from request:
Started PATCH "/hr/admin/news_items/37" for 127.0.0.1
Processing by Admin::NewsItemsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"blablablablablaabllba",
"commit"=>"Save content to page", "news_item"=>{"name"=>"test new",
"title"=>"", "body"=>"", "author"=>"", "page_id"=>"on"},
"locale"=>"hr", "id"=>"37"}
And here is item hash from console:
2.0.0p353 :124 > NewsItem.find(37)
NewsItem Load (0.3ms) SELECT "news_items".* FROM "news_items" WHERE "news_items"."id" = ? LIMIT 1 [["id", 37]]
=> #<NewsItem id: 37, name: "test new", url: nil, title: "", body: "", author: "",
page_id: 0, user_id: 7, created_at: "nvm", updated_at: "nvm">
Please note that I tried to google this, but couldn't find anything...
UPDATE:
The way i realized this was happening was because I have following routes:
resources :pages do
resources :news_items, except: [:index, :show]
end
resources :news_items
I was trying to enable CRUD for :news_items both with and without page_id in url. So after a delete I was trying to redirect to a proper route depending on values in params.
if params[:news_item].key? :page_id and not params[:news_item][:page_id].nil?
admin_page_path(Page.find(params[:news_item][:page_id]))
else
admin_news_items_path
end
So if :page_id is not nil route to corresponding page, else route to NewsItem#index.
But I kept getting an error saying:
ActiveRecord::RecordNotFound in Admin::NewsItemsController#update
Couldn't find Page with id=on
If I pass zero instead of nil, everything works as expected. Is this a good way to represent that a row does not have foreign key?
I have a list on the webpage generated from database.
It first shows what I want : Beaf .
However after this information, some others information of the array show up automatically:
<Ingredient id: 1, name: "Beaf", groupid: 1, created_at: nil, updated_at: nil>
How can I remove it? Thank you very much!
# Instead of using
<%= #ingredients.each do |i| %>
# use
<% #ingredients.each do |i| %>
The = will output all ingredients, whereas your output should only occur in the loop itself
i have a view in my postgres database that returns an array on my frequencies column. unfortunately, it sometimes returns values like {NULL} (due to the raw data).
in my rails view, i have something like:
dataset = [
<% #item.each do |i| %>
{
name: "<%= i.device %>"
lng: <%= i.longitude %>
lat: <%= i.latitude %>
frequencies: <%= i.frequencies.to_s.html_safe %>
},
<% end %>
]
which appears to work great - except when it reaches a record that contains {NULL}:
in the javascript console it shows:
Uncaught ReferenceError: nil is not defined
and in the html it shows:
...
}, {
name: "blah",
lng: -122.2,
lat: 37.4,
frequencies: [nil]
}, {
...
i could fix this by iterating through the list in the controller, but i think this would be rather long winded (and a waste of cycles).
is there a way i can get the erb to output the 'correct' [] in (instead of [nil]) json when it's null?
Try this:
<%= i.frequencies.compact %>
compact example:
[nil].compact #=> []
[1,2, nil, 3, nil].compact #=> [1,2,3]
I am new on Ruby and I am trying get data from table. so when read this
<%= puts #note.inspect %> I have this this result.
[#<Note id: 1, user_id: 1, note_type: 0, text: "Barev dzez", lat: 40.2290542420142, lng: 44.420879046875, deleted: false, created_at: "2012-04-26 14:10:05", updated_at: "2012-04-26 14:10:05">]
So when I call Note.text (for instance) I got nil result. So what should I write here to get data from array?
Thanks
#note is an Array with one Note object. You need to get the element first. For example:
<%= #note.first.text %>
You are retrive record in an array so you need to call like this
<%= puts #note.first.text %>
or
<%= puts #note.last.text %> if there is only one record
But you don't specify how you are retrive records..
What I'm trying to do:
I'm trying to find out if there is a quick way to get country_select to store integers representing the countries instead of storing the country names/strings themselves. I'm using the country select gem.
Possible solution:
One way I'm thinking this can be done is if I install the gem as a plugin and edit the countries array to have arrays within the main array with integers and a string e.g. COUNTRIES = [["United Kingdom", 1],["United States", 2]]
This way in my form there will be values representing the strings. Then I can have a country_id column in my profiles table where users selected countries id will be stored. I will have a separate table "countries" that will have the countries stored in it and I'll use the country_id of the profiles table to reference the correct country in the countries table.
Doing it this way would mean I would still get the good features of the gem/plugin such as having priority countries at the top of the select list. Something I don't know how to do on my own.
It would take long but it could work. If I chose this solution where would I put the plugin? vendors folder in my apps directory right?
But if there is a quicker way to do this I'd like to do it that way.
A bigger picture:
Ok I have a search form where a user can browse the sites users filtering out results by:
text typed location
gender
sexuality
marital status
country
I'm using thinking sphinx and when filtering attributes it seems that the attributes need to be represented integers because everything works but the country.
I'm using the country select gem and it seems to only store strings and not an integer representing the string.
I would like to have it store integers instead.
Here are some contants I use in my search forms:
module ApplicationHelper
GENDER = [["Select", nil],["Male", 1],["Female", 2]]
ETHNICITY = [["Select", nil],['Black', 1 ],['White / Caucasian', 2 ],['European', 3 ],['Asian', 4 ],
['Indian', 5 ],['Middle Eastern', 6 ],['Native American', 7 ],['Hispanic', 8 ],
['Mixed Race', 9 ],['Other Ethnicity', 10 ]]
MARITAL_STATUS = [[' Select', nil],['Single', 1 ],['Dating', 2 ],['In relationship', 3 ],['Married', 4 ],
['Living Together', 5 ],['Divorced', 6 ],['Separated', 7 ],['Widowed', 8 ]]
SEXUAL_PREFERENCE = [[' Select', nil],['Straight', 1 ],['Gay', 2 ],['Bi-sexual', 3 ]]
end
The search/browse form:
<%= form_tag browsers_path, :method => 'get' do %>
<p>
Location: <%= text_field_tag :location, params[:location] %>
<br />
Country: <%= country_select :country, [ "United Kingdom", "France", "Germany" ] %>
<br />
Gender: <%= select_tag :gender, options_for_select(ApplicationHelper::GENDER, params[:gender]) %>
<br />
Ethnicity: <%= select_tag :ethnicity, options_for_select(ApplicationHelper::ETHNICITY, params[:ethnicity]) %>
<br />
Marital status: <%= select_tag :marital_status, options_for_select(ApplicationHelper::MARITAL_STATUS, params[:marital_status]) %>
<br />
Sexual preference: <%= select_tag :sexual_preference, options_for_select(ApplicationHelper::SEXUAL_PREFERENCE, params[:sexual_preference]) %>
<br />
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
as you can see each array has a string and an integer. If you check out the array from the country_select gem there are just strings.
I'd appreciate an explanation of the best possible way to do what I'm trying to do and a clear example if possible.
I hope this post made sense.
Kind regards
I ended up recreating the country list from wikipedia with name of country and iso code as value. Much more straight forward and I got to store countries as their iso code and as integers making it possible to use the attribute with thinking sphinx.
Create the constant like you have for the other filters. Then use a virtual attribute to translate and set the values so that you can store the int version and not the string.
EDIT:
Maybe I do not understand what we are talking about exactly but if you are trying to store the value in a model somewhere you can do something like this:
def country_int(country_s)
country = COUNTRY[country_s]
end
def country_int
COUNTRY.key(country)
end