Accessing parameters of objects from a .each do block? - ruby

I've searched extensively for this (maybe I'm searching it wrong), but I can't seem to find any answers on this. My aim is to iterate through a bunch of comments in my database and output the info to my view. Unfortunately, my .each do block does not seem to be working.
models/comment.rb
class Comment < ActiveRecord::Base
attr_accessible :content, :photo_id, :user_id
belongs_to :user
belongs_to :photo
.
controllers/photos_controller.rb
def show
#photos = Photo.all
#photo = Photo.find(params[:id])
#user_likes = user_likes(#photo.id)
#comments = Comment.find_all_by_photo_id(#photo.id)
.
views/photos/show.html.erb
<% if !#comments.blank? %>
<% #comments.each do |c| %>
<%= link_to c.user.name, c.user_id %><br />
<%= c.content %>
<% end %>
<% end %>
.
If I use #comments.each do |c|, c.(anything), it will return nothing. I've verified this in rails console as well. However, #comments.first.content or #comments.first.user.name will return what I'm looking for. Why does .first allow me to return content and user fields, but .each do |c| returns nothing?
Here's output from the rails console:
1.9.3-p385 :072 > #comments.each do |c|
1.9.3-p385 :073 > c.content
1.9.3-p385 :074?> end
=> [#<Comment id: 1, user_id: 8, photo_id: 27, content: "lalala", created_at: "2013-04-09 15:36:22", updated_at: "2013-04-09 15:36:22">, #<Comment id: 2, user_id: 8, photo_id: 27, content: "abcd", created_at: "2013-04-09 15:42:00", updated_at: "2013-04-09 15:42:00">, #<Comment id: 3, user_id: 8, photo_id: 27, content: "abadsf", created_at: "2013-04-09 15:58:33", updated_at: "2013-04-09 15:58:33">, #<Comment id: 4, user_id: 8, photo_id: 27, content: "asdf", created_at: "2013-04-09 15:59:12", updated_at: "2013-04-09 15:59:12">]
1.9.3-p385 :075 > #comments.first.content
=> "lalala"

The output you posted from the console is normal:
You are iterating over each comments (so that the c variable in the block contains a comment)
Then you are just calling the attribute content on that instance without doing anything
So the output is the content of the variable #comments.
Now if you call puts c.content you will have what you're expecting.
Remarks:
If you're using Rails 3 (as mentioned by the tags of this question) you shouldn't use the find_by_all_ helpers but the where() method (You should have a look at this free railscast: http://railscasts.com/episodes/202-active-record-queries-in-rails-3).
You should use the Rails relations so that instead of doing Comment.find_all_by_photo_id(#photo.id) you could do #photo.comments.
You could then use this in your view:
<% if #photo.comments.present? %>
<% #photo.comments.each do |comment| %>
<%= link_to comment.user.name, comment.user_id %><br />
<%= comment.content %>
<% end %>
<% end %>

Related

Recaptcha gem needs a failed subimission on Rails7

A working form with recaptcha moved from rails6 to rails7 always arises a recaptcha validation error at first submit. On second submit it works.
= form_with url: mail_submit_path do |form|
= render partial: "err_details", locals: {field: :email}
.field
%label.label email
.control.has-icons-left
= form.text_field :email, value: #email, required: true, class: "input"
%span.icon.is-left
%i.fas.fa-envelope{:'aria-hidden' => "true"}
= render partial: "err_details", locals: {field: :captcha}
.field
.recaptcha
= recaptcha_tags
.field
.control
= form.submit "Submit", class: "button is-link"
On first submit some data is missing: from the rails logs:
I, [2022-01-18T18:42:23.795409 #1451245] INFO -- : [3c877c6c-5a2a-46e5-8ff6-5338c36d1078] Parameters: {"authenticity_token"=>"[FILTERED]", "email"=>"someone#gmail.com", "g-recaptcha-response"=>" ", "commit"=>"Submit"}
I would think it is a turbo issue, but not sure.
I was having the same issue in Rails 6.1.4. For some reason, changing
<%= recaptcha_tags %>
to
<%= recaptcha_tags(noscript: false) %>
worked for me.
I'd also like to add that I've had more success disabling Turbo for forms using recpatcha tags.
<%= form_with(model: #resource, local: true, data: { turbo: "false"}) do |f| %>

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...

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)

Rails nested attribute - wrong last output

I have a Article object with nested attributes Property.
Now I want to print it at the front in show.html.erb
I can print all attributes, but at the I get at the end an ouput that looks like a map with all objects inside. What am I doing wrong?
show.html.erb
<p>
<%= #article.properties.each do |property| %>
<li>
<b><%= property.name %></b> <%= property.value %>
</li>
<% end %>
</p>
article.rb
class Article < ActiveRecord::Base
has_many :properties
accepts_nested_attributes_for :properties
end
and the wrong html output in the browser
Property_6588 Value_6588
Property_9390 Value_9390
Property_15367 Value_15367
Property_19710 Value_19710
[#<Property id: 6588, name: "Property_6588", value: "Value_6588", article_id: 4766, created_at: "2012-04-12 13:33:23", updated_at: "2012-04-12 13:33:23">, #<Property id: 9390, name: "Property_9390", value: "Value_9390", article_id: 4766, created_at: "2012-04-12 13:33:29", updated_at: "2012-04-12 13:33:29">, #<Property id: 15367, name: "Property_15367", value: "Value_15367", article_id: 4766, created_at: "2012-04-12 13:33:41", updated_at: "2012-04-12 13:33:41">, #<Property id: 19710, name: "Property_19710", value: "Value_19710", article_id: 4766, created_at: "2012-04-12 13:33:50", updated_at: "2012-04-12 13:33:50">]
change
<%= #article.properties.each do |property| %>
to
<% #article.properties.each do |property| %>
The = sign renders the following statement, in this case the collection you're iterating through.

uploadify and paperclip on rails 3.1

i'm trying simply to upload a file using uploadify and paperclip.
This is index view:
<%- session_key = Rails.application.config.session_options[:key] -%>
$('#upload').uploadify({
'uploader' : 'uploadify.swf',
'script' : '/videos',
'cancelImg' : 'images/cancel.png',
'buttonText' : 'Add video!',
'folder' : '/public',
'auto' : true,
'scriptData' : {"<%= key = Rails.application.config.session_options[:key] %>" : "<%= cookies[key] %>",
"<%= request_forgery_protection_token %>" : "<%= form_authenticity_token %>",
},
onError : function (event, id, fileObj, errorObj) {
alert("error: " + errorObj.info);
}
});
This is my model:
class Video < ActiveRecord::Base
has_attached_file :source
validates_attachment_presence :source
end
...and this is my migration file:
class CreateVideos < ActiveRecord::Migration
def self.up
create_table :videos do |t|
t.string :source_content_type
t.string :source_file_name
t.integer :source_file_size
t.timestamps
end
end
def self.down
drop_table :videos
end
end
Now, when i upload a file, there aren't errors raised, neither client side, nor server side, but it looks like paperclip doesn't get the parameters sent him by uploadify. In fact, if i remove validation from model, resource is created without parameters.
In controller i add:
def create
logger.info(params.inspect) (1)
#video = Video.new(params[:video])
#video.save
logger.info #video.inspect (2)
end
In development.log (1) gives me
{"Filename"=>"prova.mov", "authenticity_token"=>"9q5w5LipGoBj Iac055OPbDofFU5FMbpEX675 RqOqs=", "folder"=>"/public", "_StreamVideo_Api_session"=>...
(2) without validation
#<Video id: 1, source_content_type: nil, source_file_name: nil, source_file_size: nil, created_at: "2011-10-10 12:12:38", updated_at: "2011-10-10 12:12:38">
(2) with validation
#<Video id: nil, source_content_type: nil, source_file_name: nil, source_file_size: nil, created_at: nil, updated_at: nil>
Where may be the problem?
Thank you in advance for answers!
In my view i put:
<h1>New video</h1>
<% form_for :video, :html => { :multipart => true } do |f| %>
<%= f.file_field :source%>
<% end %>
But http://localhost:3000/videos/new shows me only the title!!
the code looks ok, you should just add there encodeURI function. In Uploadify 2.1
it should work with:
'scriptData' : {
$('meta[name=csrf-param]').attr('content') : encodeURI(encodeURIComponent($('meta[name=csrf-token]').attr('content')))
}
With Uploadify 3.1:
'formData': {
$('meta[name=csrf-param]').attr('content') : encodeURI($('meta[name=csrf-token]').attr('content'))
}

Resources