Cannot get value when accessing Hash via CSV in ERB - ruby

I currently have this hash,
{ "meal" => "Bomb mi ",
"meal_type " => "Bombwiches",
"times_served" => "8AM to 3PM",
"days_served" => "Tuesday - Sunday",
"notes" => "Hoisin glazed shredded pork or tofu, fresh jalapenos, house-made pickled daikon & carrots, pickles, fresh cilantro, sriracha and a fried egg. ",
"price" => "13.25" }
that I'm able to access in irb via #menu_items[i]
The data is coming from a csv that i'm loading using Sinatra
get "/menu" do
data_file = 'rabbit-sinatra.csv'
#menu_items = []
CSV.foreach(data_file, headers: true, :encoding => 'utf-8') do |row|
#menu_items << row.to_hash
end
erb :menu
end
I'm then looping through this and pulling out any and all necessary values in erb.
<% for i in 0..70 do %>
<% if #menu_items[i]["meal_type"] == "Bombwiches" %>
<div class="menu">
<div class="foo"> <%= #menu_items[i]["meal"]%> </div>
<div class="times_served"> <%= #menu_items[i]["times_served"]%> </div>
<div class="days_served"> <%= #menu_items[i]["days_served"]%> </div>
<div class="notes"> <%= #menu_items[i]["notes"]%> </div>
<div class="price"> <%= #menu_items[i]["price"]%> </div>
</div>
<% end %>
<% end %>
Although #menu_items[i]["notes"] and all other hash parsing commands work, for some reason the initial "meal" value is not being picked up when i run
#menu_items[i]["meal"]
Instead of returning the value for meal "meal" => "Bomb mi " it returns nothing.
Not sure what I'm missing.

Cannot reproduce.
i = 1
#menu_items[i] =
{ "meal" => "Bomb mi ",
"meal_type " => "Bombwiches",
"times_served" => "8AM to 3PM",
"days_served" => "Tuesday - Sunday",
"notes" => "Hoisin glazed shredded pork or tofu, fresh jalapenos, house-made pickled daikon & carrots, pickles, fresh cilantro, sriracha and a fried egg. ",
"price" => "13.25" }
puts #menu_items[i]["price"] #=> "13.25"
puts #menu_items[i]["meal"] #=> "Bomb mi "
Clearly it doesn't contain what you think it does.

Related

Heroku records a fixnum instead of a string

Locally it records a string as expected and on Heroku it records a fixnum...
A user can create a wish and select an area where he wants to see a concert. In order to receive an email if a concert matches his wish.
I have a hash sotred in my application_helper.rb as a constant
DEPARTMENTS = {
"01" => "Ain",
"02" => "Aisne",
"03" => "Allier"
#........
}
My create method in the wanted_concerts_controller.rb looks like this
def create
#wanted_concert = WantedConcert.new(wanted_concerts_params)
#wanted_concert.user_id = current_user.id
if #wanted_concert.save!
redirect_to wanted_concerts_path, notice: "Ton souhait est bien enregistré"
else
render :new , alert: "Oups recommence!"
end
end
private
def wanted_concerts_params
params.require(:wanted_concert).permit(:department, :user_id)
end
In the new.html.erb file I can make my wish
<%= simple_form_for(#wanted_concert) do |f| %>
<%= f.input :department, prompt: "Choisi une région", label: false, collection: ApplicationHelper::DEPARTMENTS.map { |k, v| v } %>
<%= f.submit "Valider", class: "btn btn-success" %>
<% end %>
And this is my index.html.erb where the wishes are displayed
<% #wanted_concerts.each do |wanted| %>
<li> <%= wanted.department %> <%= link_to "Supprimer", wanted_concert_path(wanted), method: :delete %></li>
<% end %>
So locally if I chose for exemple Ain
the index display Ain
and on Heroku if chose Ain
it display 0
So On Heroku console I did:
irb(main):004:0> c = WantedConcert.last
D, [2018-03-04T13:31:54.314672 #4] DEBUG -- : WantedConcert Load (1.3ms) SELECT "wanted_concerts".* FROM "wanted_concerts" ORDER BY "wanted_concerts"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> #<WantedConcert id: 21, department: 0, user_id: 1, created_at: "2018-03-04 13:02:16", updated_at: "2018-03-04 13:02:16">
irb(main):005:0> c.department.class
=> Integer
irb(main):006:0>
I found help.
I did a naughty mistake, I renamed a field in an old migration instead of renaming in a new....
So this may help someone facing a smiliar error...

Ruby on Rails - update fields based on f.select value

I have a dropdown box to chose the number of tickets that one wants to buy. I want to update the fields after it to reflect the value once it is clicked. Here is a snippet of my form currently:
<%= form_for :transaction, :url => new_transaction_path(:event_id => #event.id), :method => 'GET' do |f| %>
<table style="width:100%">
<tr style="border-bottom: 1px solid #999999">
<td><h4>Number of Guests</h4></td>
<td>
<%= f.select(:quantity, (1..20))%>
</td>
</tr>
<tr style="border-bottom: 1px solid #999999">
<!-- replace (1) with the value from the f.select dropdown -->
<td><h4><%= #original_event_price %> x (1) guest(s)</h4></td>
</tr>
</table>
<%= f.submit 'Request to Book', class: 'button mt1 btn-request-to-book' %>
<% end %>
I want to replace (1) with the value from the f.select dropdown in the last table row to the value of guests that the user chooses.
EDIT WITH WORKING SOLUTION
<%= form_for :transaction, :url => new_transaction_path(:event_id => #event.id), :method => 'GET' do |f| %>
<table style="width:100%">
<tr style="border-bottom: 1px solid #999999">
<td><h4>Number of Guests</h4></td>
<td>
<%= f.select :quantity, (1..20), {}, { :onChange=>'mytest()', :id=>'quantitySelect' } %>
</td>
</tr>
<tr style="border-bottom: 1px solid #999999">
<!-- replace (1) with the value from the f.select dropdown -->
<td><h4><%= #original_event_price %> x (1) guest(s)</h4></td>
</tr>
</table>
<%= f.submit 'Request to Book', class: 'button mt1 btn-request-to-book' %>
<% end %>
SCRIPT
<script type="text/javascript">
function mytest() {
var quantity = $('#quantitySelect').val();
$('#quantityRow').html("<h4><%= #original_event_price %> x (" + quantity + ") guest(s)");
}
</script>
Problem : How to load value in other field based on drop-down selection
Solution:
<div class="field form-group">
<%= form.label :grade %>
<%= form.select(:grade, options_for_select(['A', 'B', 'C', 'D', 'E', 'F']), {:include_blank => 'Select Grade'}, class:"form-control", placeholder:"Grade", onchange: "loadRemarksBasedOnGrade()") %>
</div>
<div class="field form-group">
<%= form.label :remarks %>
<%= form.text_field :remarks, class:"form-control", placeholder:"Remarks", readonly: true %>
</div>
JavaScript :
<script type="text/javascript">
function loadRemarksBasedOnGrade() {
var grades = [];
grades['A'] = "Excellent";
grades['B'] = "Very Good";
grades['C'] = "Good";
grades['D'] = "Average";
grades['E'] = "Below average";
grades['F'] = "Failed";
let grade = document.getElementById("student_grade");
if(grades[grade.value] !== undefined) {
document.getElementById("student_remarks").value = grades[grade.value];
} else {
document.getElementById("student_remarks").value = "";
}
}
</script>
Note: So onchnage event loadRemarksBasedOnGrade update value based on id.
You can do this with jQuery:
Let's add an id: "quantitySelect" on the quantity field
Let's also add an id: "quantityRow" on the td field
$(function(){
$('.quantitySelect').change(function(e){
e.preventDefault();
var quantity = $('.quantitySelect').val();
$('.quantityRow').html("<h4><%= #original_event_price %> x (" + quantity + ") guest(s)");
});
});
You can also add if checks to see if the quantity is > 1 and append the word guest to guests.

Ruby templating engine Slim block confusion

I am new to slim and I find it a bit confusing.. so I have this code
td Tags: == item.tag_list.map { |t| link_to t,tag_path(t) }.join(', ')
I am having this output
<td tags:="#<Enumerator:0xbb6e8b4>">{ |t| link_to t,tag_path(t) }.join(', ') </td>
Basically I want the output to be "Tags: tag1,tag2,tag3"
How to get out of the td tag in slim?
edit:
Added a bit more code:
-#items.each do |item|
tr
td = item.title
td = item.description
td = item.price
td = item.user.username
td = item.categories.map { |c| c.name }.join{', '}
- if params[:user_id].nil?
td = link_to 'Show', item_path(item)
- else
td = link_to 'Show', edit_user_item_path(#user,item)
td = link_to 'Edit', edit_user_item_path(#user,item)
td = link_to 'Destroy', user_item_path(#user,item), method: :delete, data: { confirm: 'Are you sure?' }
td Tags: == item.tag_list.map { |t| link_to t,tag_path(t) }.join(', ')
edit: I tried this
- tags = item.tag_list.map { |t| link_to t,tag_path(t) }.join(', ').html_safe
td = "Tags: #{tags}"
but now html_safe is not working so I have this output
Tags:<a href="/tag/tag3">tag3</a>, <a href="/tag/tag2">tag2</a>, <a href="/tag/tag1">tag1</a>
I solved my own problem here is what I did
- tags = item.tag_list.map { |t| link_to t,tag_path(t) }.join(', ').html_safe
<td>Tags: #{tags}</td>
Got it working now like it supposed to.

Why can't I display the next three future events from my model?

I am attempted to display the next three future events from my database but the code below displays nothing. I can't see what I have done wrong.
This is the event controller:
class EventsController < ApplicationController
def show
#event = Event.where(:slug => params[:slug]).first
#future_events = Event.where('end_date > ?', Date.today).order('end_date ASC').limit(3)
General.first.get_blog
General.first.get_twitter
if #event.nil?
#event = Event.first
end
#days = [
{ speakers: #event.sessions.day1_speakers, workshops: #event.sessions.day1_workshops },
{ speakers: #event.sessions.day2_speakers, workshops: #event.sessions.day2_workshops }
]
end
end
And this is the event view:
<% #future_events.first(3).each do |e | %>
<div class="fourcol aboutColumn">
<h3><%= e.title %></h3>
<p><%= e.start_date.strftime("%e %B %Y") %>, <%= e.venue_title %></p>
<p><%= e.event_description %></p>
</div>
<% end %>
You should structure your query to return only the events you need:
Event.where('end_date > ?', Date.today).order('end_date ASC').limit(3)
Beyond that, I can't see why nothing is displayed. Can you post your entire controller method?
Update:
This is the equivalent query for Mongoid:
Event.where(:end_date.gt => Date.today).sort(:end_date => 1).limit(3)

problem in Adding image in MVC3

I am using this code in mVC2 and it is working Fine for me. But when i convert it into mvc3 this code give me error. Please tell me how i convert it into mvC3. The code is
<% Html.Grid(Model.MemberPagedList).Columns(column => {
column.For(x => x.Id).Named("Id");
column.For(x => x.message).Named("Message").Action(p =>
{ %>
<td> some image tag here
</td>
<td style="display: none; " id =<%= p.Id%>>
<%= p.LogMessage %>
</td>
<% });
}).RowStart((p,row) => {
if (row.IsAlternate) { %>
<tr >
<% } else { %>
<tr>
<% }
}).Sort(Model.GridSortOptions).Attributes(#class => "table-list").Render(); %>
I am Replacing <% %> with # But it is not working. I am not able to understand how i write Html Code ie <td>.....</td>
<td style="display: none;" id=<%= p.Id%>>
<%= p.LogMessage %>
</td>
in mvc3
You could use a custom column to add an image to an MVCContrib Grid:
#(Html
.Grid<MyViewModel>(Model.MemberPagedList)
.Columns(column =>
{
column.For(x => x.Id);
column.For(x => x.LogMessage);
column
.Custom(
#<text>
<span>#item.LogMessage</span>
<img src="#Url.Action("image", new { id = item.Id })" alt="" />
</text>
)
.Named("Message");
})
.Sort(Model.GridSortOptions)
.Attributes(new Hash(#class => "table-list"))
)

Resources