Do..end loop just returning main array - arrays

Can anyone help me to find problem here?
#deals.each.with_index(1) do |deal, i|
binding.pry
puts "#{deal.title} - #{deal.price} - Rating: #{deal.deal_rating}"
# puts "Available for #{deal.price}"
# puts "Rating: #{deal.deal_rating}"
# puts "#{deal.title}"
# puts "Available at "
end
If I do binding.pry, and try to check the value of deal here, it is returning me complete #deals array rather than one deal.
Thank you so much in advance for your help.

Use just each_with_index which will give you the object and the index inside the total of elements being iterated:
<% #deals.each_with_index do |deal, i| %>
<% binding.pry %>
<%= "#{deal.title} - #{deal.price} - Rating: #{deal.deal_rating}" %>
<% end %>
This way inspecting with pry you take the first element from #deals:
[1] pry(#<#<Class:0x007fe0cd161ee8>>)> #deals.first
=> #<Deal:0x007fe0cb2751d8
id: 1,
title: "Deal-0",
price: 764,
deal_rating: 93,
created_at: Sat, 01 Apr 2017 15:00:29 UTC +00:00,
updated_at: Sat, 01 Apr 2017 15:00:29 UTC +00:00>
If you want to do it in your views then use unless to check for the first element using the index:
<% #deals.each_with_index do |deal, i| %>
<% unless !i.zero? %>
<%= "#{deal.title} - #{deal.price} - Rating: #{deal.deal_rating}" %>
<% end %>
<% end %>
The difference is that with with_index you can use an optional parameter to offset the starting index, so you're specifying the index from where to start with with_index(1) not trying to get the first element, see this:
<% #deals.each.with_index(2) do |deal, index| %>
<%= "#{index}: #{deal}" %><br>
<% end %>
2: #<Deal:0x007fe0cb55ca90>
3: #<Deal:0x007fe0cb55c950>
4: #<Deal:0x007fe0cb55c810>
...
This starts from the index 2, and the other one from 0.
<% #deals.each_with_index do |deal, index| %>
<%= "#{index}: #{deal}" %><br>
<% end %>
0: #<Deal:0x007fe0cb55ca90>
1: #<Deal:0x007fe0cb55c950>
2: #<Deal:0x007fe0cb55c810>
3: #<Deal:0x007fe0cb55c6d0>
4: #<Deal:0x007fe0cb55c590>

Related

Get iterator index in go template (consul-template)

I'm trying to get a simple index that I can append to output of a Go template snippet using consul-template. Looked around a bit and couldn't figure out the simple solution. Basically, given this input
backend web_back
balance roundrobin
{{range service "web-busybox" "passing"}}
server {{ .Name }} {{ .Address }}:80 check
{{ end }}
I would like to see web-busybox-n 10.1.1.1:80 check
Where n is the current index in the range loop. Is this possible with range and maps?
There is no iteration number when ranging over maps (only a value and an optional key). You can achieve what you want with custom functions.
One possible solution that uses an inc() function to increment an index variable in each iteration:
func main() {
t := template.Must(template.New("").Funcs(template.FuncMap{
"inc": func(i int) int { return i + 1 },
}).Parse(src))
m := map[string]string{
"one": "first",
"two": "second",
"three": "third",
}
fmt.Println(t.Execute(os.Stdout, m))
}
const src = `{{$idx := 0}}
{{range $key, $value := .}}
index: {{$idx}} key: {{ $key }} value: {{ $value }}
{{$idx = (inc $idx)}}
{{end}}`
This outputs (try it on the Go Payground) (compacted output):
index: 0 key: one value: first
index: 1 key: three value: third
index: 2 key: two value: second
See similar / related questions:
Go template remove the last comma in range loop
Join range block in go template
Golang code to repeat an html code n times
The example below looks for all servers providing the pmm service, but will only create the command to register with the first pmm server found (when $index == 0)
{{- range $index, $service := service "pmm" -}}
{{- if eq $index 0 -}}
sudo pmm-admin config --server {{ $service.Address }}
{{- end -}}
{{- end -}}

Rails 4 Nested Attributes with fields_for Don't Save to Database

I want to create records on two different tables (venue and parking) via one form using accepts_nested_attributes_for. I want a user to be able to create a new venue, and also specify the parking options available to that venue via checkboxes. When I submit the form, the record for the containing model (venue) is created, but nothing happens with the nested model (parking). When I check the response from the server, I see that I'm encountering "Unpermitted parameters: parking_attributes," although I'm not sure why.
I've watched Railscast #196 Nested Model Form, and tried the suggestions from multiple stackoverflow posts (Rails 4 nested attributes not saving, Rails 4: fields_for in fields_for, and Rails 4 - Nested models(2 levels) not saving). If anybody can help me out, I'd greatly appreciate it.
I've included the two models, the venues controller, the venues/new view, and the response from the server.
venue.rb
class Venue < ActiveRecord::Base
has_many :parkings
accepts_nested_attributes_for :parkings
end
parking.rb
class Parking < ActiveRecord::Base
belongs_to :venue
end
venues_controller.rb
class VenuesController < ApplicationController
def index
#venues = Venue.all
end
def new
#venue = Venue.new
end
def create
#venue = Venue.new(venue_params)
if #venue.save
redirect_to #venue, flash: { success: "Venue successfully created" }
else
render :new
end
end
def show
#venue = Venue.find(params[:id])
end
def edit
#venue = Venue.find(params[:id])
end
def update
#venue = Venue.find(params[:id])
if #venue.update(venue_params)
redirect_to #venue
else
render "edit"
end
end
def destroy
#venue = Venue.find(params[:id])
if #venue.destroy
redirect_to venues_path, flash: { success: "Venue successfully destroyed" }
else
render "show", flash: { error: "Venue was not successfully destroyed" }
end
end
private
def venue_params
params.require(:venue).permit(
:name,:address,:city,:state,:zip,
parking_attributes: [:id, :venue_id, :none, :street_free])
end
end
/venues/new.haml
%h1 Add a new venue
= form_for #venue do |f|
= f.label :name
= f.text_field :name
= f.label :address
= f.text_field :address
= f.label :city
= f.text_field :city
= f.label :state
= f.text_field :state
= f.label :zip
= f.text_field :zip
= f.fields_for :parkings do |p|
= p.label :none
= p.check_box :none
= p.label :street_free
= p.check_box :street_free
= f.submit
Server response
Started POST "/venues" for 127.0.0.1 at 2014-04-29 14:02:54 -0500
Processing by VenuesController#create as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"kMcVVwXq7f22rIGm1rQ6+QzC80ScmXrVA2IE8TGbN7w=",
"venue"=>{"name"=>"The Five O'Clock Lounge",
"address"=>"11904 Detroit Ave",
"city"=>"Lakewood",
"state"=>"OH",
"zip"=>"44107",
"parkings_attributes"=>
{"0"=>
{"none"=>"1",
"street_free"=>"0"
}
}
},
"commit"=>"Create Venue"}
Unpermitted parameters: parkings_attributes
(0.2ms) BEGIN
SQL (107.0ms) INSERT INTO "venues" (
"address",
"city",
"created_at",
"name", "state",
"updated_at", "zip"
) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"
[
["address", "11904 Detroit Ave"],
["city", "Lakewood"],
["created_at", Tue, 29 Apr 2014 19:02:54 UTC +00:00],
["name", "The Five O'Clock Lounge"],
["state", "OH"],
["updated_at", Tue, 29 Apr 2014 19:02:54 UTC +00:00],
["zip", 44107]
]
SQL (47.5ms) INSERT INTO "parkings" (
"created_at",
"updated_at",
"venue_id") VALUES ($1, $2, $3) RETURNING "id"
[
["created_at", Tue, 29 Apr 2014 19:02:54 UTC +00:00],
["updated_at", Tue, 29 Apr 2014 19:02:54 UTC +00:00],
["venue_id", 10]
]
(0.6ms) COMMIT
Redirected to http://localhost:3000/venues/10
Completed 302 Found in 165ms (ActiveRecord: 155.2ms)
UPDATE: SOLVED
Following the advice of Kirti, I was able to get past the unpermitted parameters error.
Update venue_params method as below:
def venue_params
params.require(:venue).permit(
:name,:address,:city,:state,:zip,
parkings_attributes: [:id, :venue_id, :none, :street_free])
end
Notice parkings_attributes(plural parkings) and not parking_attributes(singular parking).
As you have 1-M relationship between Venue and Parking model you would receive parkings_attributes(plural parkings) in params hash BUT in your current code for venue_params you whitelisted parking_attributes(singular parking). This is causing the warning Unpermitted parameters: parkings_attributes

Store several text_field strings to array Rails 3

I'm trying to store some strings from a couple of text_fields that i have into an array, and then save it to the DB.
I have a column named "opening_hours" wich I've tried to separate into 2 different attributes using virtual attributes like this:
Model
class Venue < ActiveRecord::Base
attr_accessible :opening_hours, :start_time, :end_time
attr_writer :start_time, :end_time
def start_time
#start_time.nil? ? #start_time : opening_hours.to_s.split("-").first
end
def end_time
#end_time.nil? ? #end_time : opening_hours.to_s.split("-").last
end
end
The idea is that you type in a start_time and an end_time like this:
View
<%= form_for #venue do |v| %>
<p><%= v.label "Monday" %><%= v.text_field :start_time %>-<%= v.text_field :end_time %><p/>
<p><%= v.label "Tuesday" %><%= v.text_field :start_time %>-<%= v.text_field :end_time %><p/>
<p><%= v.label "Wednesday" %><%= v.text_field :start_time %>-<%= v.text_field :end_time %><p/>
<% end %>
The array should look something like this in the DB:
{08-12|09-14|07-13}
With the "|" separating the different days of the week.
I've tried a couple of things in the controller like:
Controller
class VenuesController < ApplicationController
def new
#venue = Venue.new
end
def create
#venue = Venue.new(params[:venue])
#total_time = params[:venue][:start_time]+"-"+params[:venue][:end_time]
#venue.opening_hours = #total_time.map {|t| [t.start_time, t.end_time]}
if #venue.save
redirect_to venue_path(#venue), :notice => "Success!"
else
render 'new'
end
end
But nothing seems to work... either it just saves start_time and end_time from the last day, or nothing gets saved at all.
I perhaps may have misunderstood, but...
In your create action, there is no #venue.save - this could be why you are not seeing anything saved.
class VenuesController < ApplicationController
def new
#venue = Venue.new
end
def create
#venue = Venue.new(params[:venue])
#total_time = params[:venue][:start_time]+"-"+params[:venue][:end_time]
#venue.opening_hours = #total_time.map {|t| [t.start_time, t.end_time]}
#venue.save
end
end
Your solution will not work, since you place three text-fields each pointing to the same field. Rails will just take the last value.
Rails will use the name of the input field to construct the parameters hash you receive at the server. Since the fields have the same name, only one value will remain.
The solution is pretty simple: using the same rails standards, we can change the name of the input fields so rails will handle it as a hash.
<p>
<%= v.label "Monday" %>
<%= text_field :venue, 'start_time[][monday]', :value => '07' %>
<%= text_field :venue, 'end_time[][monday]', :value => '21' %>
<p/>
<p>
<%= v.label "Tuesday" %>
<%= text_field :venue, 'start_time[][tuesday]', :value => '07' %>
<%= text_field :venue, 'end_time[][tuesday]', :value => '09' %>
<p/>
Since end_time and start_time is not a array, I have to fake it a bit, so I use a manual text_field, use as object-name venue so it will be grouped with the rest of the parameters for your venue. Then I build the name, so rails will compose a hash with the values entered. Note, you have to explicitly define a value, or this will not work.
Then, in the controller, you will have to add some code to
when editing, convert the array-string to values in your form
when saving, convert the recevied hash to a string you can save.
Note: if you do not, it will save the serialized hash, which might just be enough already.

Mongoid each.with_index not working

I can do this in plain ruby
[3,2,1].each.with_index do |e, i|
p e, i
end
3
0
2
1
1
2
But I can't do this with Mongoid:
Model.each.with_index do |e, i|
p e, i
end
It fails with
undefined method with_index for Array
How can I fix this without using this:
Model.each_with_index
Which does not allow starting index to be set
In Mongoid 3.1.3, with_index method works as expected.
puts Mongoid::VERSION
class User
include Mongoid::Document
field :name, type: String
end
User.create([
{ name: 'Harai' },
{ name: 'Sasaki' }
])
User.each.with_index do |u, i|
puts "#{u.name}, #{i}"
end
The above code works like this:
$ ruby main.rb
3.1.3
Harai, 0
Sasaki, 1
Your problem might be because you are using older version of Mongoid.

Server.Execute Duplicates Dynamic Content

I created a page in ASP that loads dynamic content with code similar to this:
<%
var1 = int(rnd * 5) + 1
var2 = int(rnd * 10) + 1
%>
<html>
<body>
what variable 1 is: <%=var1%>
what variable 2 is: <%=var2%>
</body>
</html>
Then I have another page that uses Server.Execute to execute the previous file mentioned 2+ times using a loop. The code looks like this:
<% filename = request.querystring("page") %>
<table class="domtable">
<% for j = 1 to 2%> <%qnumb = qnumb + 1%>
<tr>
<td align="left">
<%server.execute (filename)%>
<% If qnumb < 2 then%>
<br/><hr><br/>
<%end if%>
</td></tr>
<%next%>
</table>
So for the last couple of months this has been working perfectly for me, loading different numbers for both variables on the two separate executions. Then today, I duplicated a folder on my server, renamed it and now magically, the variables are the same number about 9 out of 10 times the browser is refreshed.
This happened to me with the same files on my second server a month ago, and I had to delete all the files off of the second server, and download them from my first server (the one duplicating now), then upload them back and that fixed it. Unfortunately, I didn't download the entire server contents of my first server so I'm unable to reverse the process. So I'm not sure if this issue is server-side, or if it's related with the code I'm writing? I just don't know why it would work for so long then just stop working out of nowhere.
I've tried using meta no-cache controls. I deleted the new folder I duplicated earlier from the server and that didn't work. I also tried deleting files from the last couple days that have been uploaded and that didn't work either. I've tried loading 'filename' as an array such as:
filename(1) = request.querystring("page")
filename(2) = request.querystring("page")
for j = 1 to 2
Server.Execute(filename(j))
next
I really hope someone knows what I'm doing wrong here.
-EDIT-
I'm also doing this and getting the same results.
<%
'rnd.asp'
pStr = "private, no-cache, must-revalidate"
Response.ExpiresAbsolute = #2000-01-01#
Response.AddHeader "pragma", "no-cache"
Response.AddHeader "cache-control", pStr
server.execute ("rndj.asp")
response.write ("<hr>")
randomize(3)
server.execute ("rndj.asp")
%>
<%
'rndj.asp'
pStr = "private, no-cache, must-revalidate"
Response.ExpiresAbsolute = #2000-01-01#
Response.AddHeader "pragma", "no-cache"
Response.AddHeader "cache-control", pStr
randomize
response.write rnd
response.write "<br>"
response.write rnd
%>
I started to use this code below which looks at the specified file as plain text and removes the asp tags from it then uses Execute to run it within the original file. The problem with this is all my pages that i call use in them for other resources and the replace script wont let me add asp tags around the include lines.
<%
Dim sTargetFile, sTargetFileContents
Dim oFSO, sContents
Function GetFileContentsForExecution(sTargetFile)
'Obtain a reference to the FileSystemObject
Set oFSO = Server.CreateObject("Scripting.FileSystemObject")
'Obtain the file contents
sContents = oFSO.OpenTextFile(Server.MapPath(".") & "\" & sTargetFile).ReadAll
Set oFSO = Nothing 'reference to the FileSystemObject
'Remove the ASP scripting tags
rand = int(rnd * 2)
sContents = Replace (sContents, "<" & "%", "")
sContents = Replace (sContents, "%" & ">", "")
GetFileContentsForExecution = sContents
End Function
sTargetFile = "rndj.asp"
for j = 1 to 6
'Get the contents of the file to execute
sTargetFileContents = GetFileContentsForExecution(sTargetFile)
Execute sTargetFileContents
next
if j < 3 then
response.write ("<br/><hr><br/>")
end if
%>
Link to working solution
<%
'rnd.asp'
randomize
application("randomseed") = rnd
server.execute ("rndj.asp")
application("randomseed") = rnd
server.execute ("rndj.asp")
%>
<%
'rndj.asp'
randomize application("randomseed")
response.write rnd
response.write("<br />")
response.write rnd
response.write("<br />")
response.write("<br />")
%>

Resources