undefined method `strftime' for nil:NilClass - Comment Date - ruby-on-rails

I am displaying the date when a comment is published:
<%= comment.created_at.strftime("%d %b %Y") %>
This works, except if the comment is not filled out correctly, and is submitted. If this occurs I get the error: undefined methodstrftime' for nil:NilClass` instead of my comment validations.
How to fix this, I am not sure?
Here's my code:
class CommentsController < ApplicationController
def create
#post = Post.friendly.find(params[:post_id])
#comment = #post.comments.create(params[:comment].permit(:name, `:email, :website, :body, :url))`
if #comment.errors.any?
render "posts/show"
else
redirect_to post_path(#post)
end
end
def destroy
#post = Post.friendly.find(params[:post_id])
#comment = #post.comments.find(params[:id])
#comment.destroy
redirect_to post_path(#post)
end
end
class Comment < ActiveRecord::Base
belongs_to :post
validates_format_of :email, :with => /#/
validates :name, presence: true, length: { minimum: 5}
validates :body, presence: true, length: { minimum: 5}
validates :body, presence: true, length: { minimum: 5}
def gravatar_url
stripped_email = email.strip
downcased_email = stripped_email.downcase
hash = Digest::MD5.hexdigest(downcased_email)
default_url = "https://s3-us-west-2.amazonaws.com/mirror-communications/assets/download.jpg"
"http://gravatar.com/avatar/#{hash}"
end
end
<!-- Post Comments Partial -->
<li>
<article class="comment">
<div class="user-avatar">
<%= image_tag comment.gravatar_url %>
</div>
<div class="comment-content">
<h5 class="name"><%= comment.name %></h5>
<div class="comment-meta comment-reply">
<span class="post-date"><%= comment.created_at.strftime("%d %b %Y") %></span>/<span class="comment-reply-link"><%= link_to comment.website.try(:remove, /.*\/\//), url_for(comment.website), target: '_blank', class: "comment-reply" %></span>
</div>
<p><%= comment.body %></p>
</div>
</article>
<!-- Form Partial -->
<%= form_for([#post, #post.comments.build]) do |f| %>
<% if #comment && #comment.errors.any? %>
<div id="error_explanation" class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h2><%= pluralize(#comment.errors.count, "error") %> Your comment could not be submitted:</h2>
<ul>
<% #comment.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<form class="comment-form">
<div class="row">
<div class="column width-4">
<%= f.text_field :name, class: "form-name form-element", placeholder: "Name*", :tabindex => 1 %>
</div>
<div class="column width-4">
<%= f.email_field :email, class: "form-email form-element", placeholder: "Email* (not displayed)", :tabindex => 3 %>
</div>
<div class="column width-4">
<%= f.url_field :website, class: "form-website form-element", placeholder: "Website", :tabindex => 4 %>
</div>
</div>
<div class="row">
<div class="column width-12">
<%= f.text_area :body, class: "form-message form-element", placeholder: "Message*", :tabindex => 5 %>
<%= f.submit class: "form-submit button medium bkg-black bkg-hover-turquoise color-white color-hover-white no-margin-bottom" %>
</div>
</div>
</form>
</div>
<% end %>
<!-- Posts Show -->`
<div class="post-comments">
<h3 class="comments-title">
<% if #post.comments.count < 2 %>
<%= #post.comments.count %> Comment</h3>
<% else %>
<%= #post.comments.count %> Comments</h3>
<% end %>
<div class="comments">
<ul class="comment-list">
<%= render #post.comments %>
</ul>
</div>
</div>

I think you have not populated local variable comment properly.
try this,
comment.created_at.strftime("%d %b %Y") if comment and comment.created_at

Related

I am working on Ruby on rails but it is giving undefined method `errors' for nil:NilClass error

Don't know why my app is throwing error on the registration file.Plz let me know the error.Thank you very much
Error
Showing /home/punisher/Desktop/billboard/app/views/register/signup.html.erb where line #36 raised:
undefined method `errors' for nil:NilClass
Extracted source (around line #36):
<h1 class="Login-here">Register Here</h1>
<%= form_with model: #owner,url:register_path, local: true do |form| %>
<% if #owner.errors.any? %>
<div class="alert alert-danger">
<% #owner.errors.full_messages.each do |message| %>
<div> <%= message %> </div>
Register_controller
class RegisterController < ApplicationController
def new
#owner=Owner.new
end
def create
# render plain: "Thanks for registering!"
# render plain: params[:user]
#owner=Owner.new(owner_params)
if #owner.save
session[:owner_id] = #owner.id
redirect_to login_path
else
flash[:error] ="User Not Registered"
render :signup
end
end
private
def owner_params()
params.permit(:email, :company_name, :address, :contact_no, :password, :password_confirmation)
end
end
signup.erb.html
<body style = "background-color:rgb(92, 179, 196)">
<div class="tnavbar">
<div class="tlogo">
<%= image_tag('1.png', :class => "logoimg") %>
<h3 class="title"> Out of Home</h3>
</div>
<div>
<%= link_to "login", login_path, class:"home-btn"%>
</div>
</div>
<div class="container-fluid" style="margin-top:50px;">
<div class="row loginpagerow">
<div class="col-1">
</div>
<div class="logincol col-5 imagebox">
<h1 class="headinglogin">Bringing you the best of the best.</h1>
<%= image_tag('loginpageimage.png', :class => "img") %>
</div>
<div class="col-5 logincol loginbox">
<h1 class="Login-here">Register Here</h1>
<%= form_with model: #owner,url:register_path, local: true do |form| %>
<% if #owner.errors.any? %>
<div class="alert alert-danger">
<% #owner.errors.full_messages.each do |message| %>
<div> <%= message %> </div>
<% end %>
</div>
<% end %>
<div class="row" style="margin-top:30px">
<div style="width:45%; height:35vh; margin-left:25px;">
<%= form.email_field :email ,class: "form-control login-email-field signup-fields", placeholder:"Email" %>
<%= form.text_field :company_name ,class: "form-control login-email-field signup-fields", placeholder:"Company Name" %>
<%= form.text_field :address ,class: "form-control login-email-field signup-fields", placeholder:"Address" %>
</div>
<div style="width:45%; height:35vh; margin-left:25px;">
<%= form.telephone_field :contact_no ,class: "form-control login-email-field signup-fields", placeholder:"Contact No" %>
<%= form.password_field :password ,class: "form-control login-email-field signup-fields", placeholder:"password" %>
<%= form.password_field :password_confirmation,class: "form-control login-email-field signup-fields", placeholder:"Confirm password" %>
</div>
<div class="mb-3 login-input">
<%= form.submit "Signup" ,class: "sign-btn btn btn-primary"%>
</div>
</div>
<% end %>
</div>
<div class="col-1">
</div>
</div>
</div>
</body>
You have a app/views/register/signup.html.erb view and Rails expects signup method in your registrations_controller and is looking for #owner
instance method but you don't have signup method that's why it's raising an error because #owner is nil.
def signup
#owner = Owner.new(owner_params)
...
end

undefined local variable or method `form' for Class

When I'm attempting to show a department view on my product#new page, this is my product#new page
<% #produto.errors.full_messages.each do |msg| %>
<div class="alert alert-danger" role="alert">
<%= msg %>
</div>
<% end %>
<%= form_for #produto do |produto| %>
<div class="row">
<div class="col-sm-3">
<div class="form-group">
<%= produto.label :nome %>
<%= produto.text_field :nome, class:"form-control" %>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-3">
<div class="form-group">
<%= produto.label :descricao %>
<%= produto.text_area :descricao, class:"form-control", rows:"4" %>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-2">
<div class="form-group">
<%= form.label :departamento %>
<%= form.collection_select :departamento_id, #departamentos, :id, :nome, {}, class:"form-control" %>
</div>
</div>
</div>
<%= produto.submit "Criar",class:"btn btn-success" %>
<% end %>
This is my product_controller.rb
class ProdutosController < ApplicationController
def index
#produtos = Produto.order(nome: :asc).limit 5
#produtos_com_desconto = Produto.order(:preco).limit 1
end
def new
#produto = Produto.new
#departamentos = Departamento.all
end
def create
valores_produto = params.require(:produto).permit(:nome, :descricao, :preco, :quantidade)
#produto = Produto.new valores_produto
#Produto.create valores_produto
if #produto.save
flash[:notice] = "Produto criado com sucesso!"
redirect_to root_url
else
render :new
end
end
def destroy
id = params[:id]
Produto.destroy id
redirect_to root_url
end
def search
#nome = params[:nome]
#produtos = Produto.where "nome like ?", "%#{#nome}%"
end
end
So, when i'm trying to access my product/new page , i'm receiving the error NameError in Produtos#new: undefined local variable or method `form' for #<#<Class.
<%= form.label :departamento %> is looking for the form variable but there is none defined. Instead <%= form_for #produto do |produto| %> has defined producto and uses it as <%= produto.label :nome %>. So you probably want <%= producto.label :departamento %>
Note the variable should probably be form. The variable is a FormBuilder, not a Produto. Calling it producto is confusing.

Can't seem to submit collection_select and receiving Unpermitted parameter: :hero_id

Sorry for the messy post, my first time posting. I have been trying to get this collection submit to work, but every time I press create report button I have it goes back to the screen and puts out Unpermitted parameter: :hero_id in the rails server terminal.
Model
class Report < ApplicationRecord
validates :subject, presence: true, length: { minimum: 6, maximum: 100 }
validates :description, presence: true, length: { minimum: 10, maximum: 300 }
belongs_to :requester
has_and_belongs_to_many :heros
end
View/Form
<div class="container">
<div class="row justify-content-center">
<div class="col-10">
<% if #report.errors.any? %>
<h2>The following errors prevented the article from being saved</h2>
<ul>
<% #report.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<%= form_with(model: #report, class: "shadow p-3 mb-3 bg-dark rounded", local: true) do |f| %>
<div class="form-group row">
<%= f.label :subject, class: "col-2 col-form-label text-light" %>
<div class="col-10">
<%= f.text_field :subject, class: "form-control shadow rounded", placeholder: "Subject of Report" %>
</div>
</div>
<div class="form-group row">
<%= f.label :description, class: "col-2 col-form-label text-light" %>
<div class="col-10">
<%= f.text_area :description, rows: 10, class: "form-control shadow rounded", placeholder: "Description of Issue" %>
</div>
</div>
<div class="form-group row">
<%= f.label :hero, class: "col-2 col-form-label text-light" %>
<div class="col-10">
<%= f.collection_select(:hero_ids, Hero.all, :id, :hero_name, {prompt: "Select a Hero"}, {:required => true}) %>
</div>
</div>
<div class="btn-toolbar p-2 mb-2 row justify-content-center">
<%= f.submit class: "btn btn-primary" %>
</div>
<% end %>
</div>
<div class="mb-3">
<%= link_to '[ Cancel and return to reports listing ]', reports_path, class: "text-info" %>
</div>
</div>
</div>
Controller
def report_params
#byebug
params.require(:report).permit(:subject, :description, hero_ids: [])
end
Console
(byebug) params.require(:report)
<ActionController::Parameters {"subject"=>"Test report", "description"=>"Test report", "hero_ids"=>"1"} permitted: false>

Rails 4 Two Forms, Separate Models On One Page

I have two models for communication, Post and Reply. For some reason I can't figure out, the #reply form is unresponsive. Submit does not work, and the file upload field does not work, but only on the #reply form, the #prosect and #post forms work perfectly.
<h1><strong><%= #group.name %></strong></h1>
<p><em><%= #group.description %></em><p>
<p>Operated by: <% #owner = User.find(#group.owner_id) %><%= #owner.name %></p>
<% if current_user.group_id == nil %>
<%= form_for(#prospect) do |f| %>
<%= f.hidden_field :group_id, value: #group.id %>
<%= f.submit "Join Group", class: "btn btn-primary" %>
<% end %>
<% end %>
<% if current_user.group_id == #group.id %>
<%= form_for(#post) do |f| %>
<%= f.hidden_field :group_id, value: #group.id %>
<%= f.hidden_field :user_id, value: current_user.id %>
<div class="form-group col-xs-12">
<div class="row">
<div class="col-xs-11">
<%= f.text_area :content, class: 'form-control', placeholder: "What ails you?" %>
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-success" onclick="addpic(0);">Add a pic</button>
</div>
</div>
</div>
<div class="form-group hidden col-xs-12" id="picture0">
<%= f.file_field :image, class: 'form-control' %>
</div>
<div class="form-group col-xs-12 actions">
<%= f.submit %>
</div>
<% end %>
<% #group.posts.each do |p| %>
<div class="post">
<div class="post-meta">
<%= p.user.name %> <em><%= p.created_at.strftime('%a, %b %e, %Y %r') %></em>
</div>
<%= p.content %>
<% if p.image %>
<img src="data:image/png;base64,<%= p.image %>" class="img-responsive"/>
<% end %>
<% p.replies.each do |r| %>
<%= r.user.name %><br/><%= r.content %>
<% if r.image %>
<img src="data:image/png;base64,<%= r.image %>" class="img-responsive"/>
<% end %>
<% end %>
<a class="reply">Reply</a>
<div class="reply hidden">
<%= form_for(#reply) do |ff| %>
<%= ff.hidden_field :post_id, value: p.id %>
<%= ff.hidden_field :user_id, value: current_user.id %>
<div class="form-group col-xs-12">
<div class="row">
<div class="col-xs-11">
<%= ff.text_area :content, class: 'form-control', placeholder: "Write a reply..." %>
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-success" onclick="addpic(<%= p.id %>);">Add a pic</button>
</div>
</div>
</div>
<div class="form-group hidden col-xs-12" id="picture<%= p.id %>">
<%= ff.file_field :image, class: 'form-control' %>
</div>
<div class="form-group col-xs-12 actions">
<%= ff.submit %>
</div>
<% end %>
</div>
</div>
<% end %>
<% end %>
<script>
var addpic = function(id) {
var el = '#picture' + id;
$(el).removeClass('hidden');
}
$('.reply').on('click', function(e){
e.preventDefault();
$(this).next().removeClass('hidden');
});
</script>
Figured out the issue, JS was preventing the default for all clicks inside a .reply div. Had reply used in the wrapper for the reply form, so it was preventing the default. Got it working now by changing the class of the reply link to 'addreply' and the js listener to 'addreply' as well.

Nested form does not validate association model

I'm using rails 3.2 with active record and sqlserver. I have a problem with nested forms. I have a model registration which has many registration details and each has a person associated.
Here is the model
class Registration < ActiveRecord::Base
set_table_name "dbo.EV_INSCRIPCIONES"
set_primary_key "Id"
belongs_to :category, :foreign_key => 'CategoriaId'
has_many :registrationDetails, :foreign_key => 'InscripcionEventoId'
#has_one :group
accepts_nested_attributes_for :registrationDetails
validates_associated :registrationDetails
validates :Refencia, :presence => true
#validates_presence_of :category_id
attr_accessible :registrationDetails, :category, :Eliminada, :FechaInscripcion, :CreationalDate, :Referencia, :PagoRegistrado, :Acreditado, :registrationDetails_attributes
#after_initialize :init
def init
write_attribute :Eliminada, false
write_attribute :Acreditado, false
write_attribute :PagoRegistrado, false
write_attribute :CreationalDate, DateTime.now
write_attribute :FechaInscripcion, DateTime.now
#write_attribute :Referencia, ''
end
def category_id
self.category.id unless category.nil?
end
def category_id=(id)
self.category = Category.find(id)
end
end
class RegistrationDetail < ActiveRecord::Base
set_table_name "dbo.EV_INSCRIPCION_DETALLE"
set_primary_key "Id"
belongs_to :registration, :foreign_key => 'InscripcionEventoId'
belongs_to :category, :foreign_key => 'CategoriaId'
belongs_to :person, :foreign_key => 'ParticipanteId', :primary_key => 'JUGADOR_ID'
attr_accessible :person, :category, :registration, :Eliminada, :person_attributes
accepts_nested_attributes_for :person
validates_associated :person
after_initialize :init
def init
write_attribute :Eliminada, false
end
end
class Person < ActiveRecord::Base
set_table_name "dbo.PKR_JUGADOR"
set_primary_key "JUGADOR_ID"
has_many :registrationDetails
validates_presence_of :CDNI, :CNOMBRES, :CAPELLIDO, :CSEXO,:CCIUDADRESIDENCIA, :DFECHANACIMIENTO
validates :CDNI, :length => { :minimum => 7, :maximum =>8 }
#validate :validate_birth_date
before_save :set_ids
def set_ids
if id.nil?
_id = Person.maximum(:JUGADOR_ID)
self.JUGADOR_ID = _id +1
write_attribute :CNROJUGADOR, _id+1
end
end
after_initialize :init
def init
write_attribute :TIPODOCUMENTO_ID, 1 if read_attribute(:TIPODOCUMENTO_ID).nil?
end
def full_name
self.surname + ", " + self.name
end
protected
def validate_birth_date
errors.add(:birth_date, 'must be a valid datetime') if ((Date.strptime(birth_date, "%d/%m/%Y") rescue ArgumentError) == ArgumentError)
end
end
My view
index.html.erb
<h1><%= t '.title', :name => #event.CNOMBRETORNEO %> </h1>
<%= render 'form_nested' %>
_form_nested
<%= form_for #registration, :url => {:controller => "registration", :action => "save"}, :html => {:class=> 'form-horizontal'} do |f| %>
<legend><%= t '.legend' %></legend>
<% if f.object.errors.any?%>
<div id="error_explanation">
<h3 class="text-error"><%= t '.has-errors' %></h3>
</div>
<% end %>
<input type="hidden" id="event_date" name="event_date" value="<%= #event.DDIAACTIVIDAD.strftime('%Y%m%d') %>" />
<input type="hidden" id="event_id" name="event_id" value="<%= #event.TORNEOPOKER_ID %>" />
<%= f.fields_for :registrationDetails do |d| %>
<%= render 'details_fields' , :f => d %>
<% end %>
<% has_error = f.object.errors.has_key? :category %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :category, :class=> 'control-label' %>
<div class="controls">
<%= f.hidden_field :category_id %>
<div class="btn-group" data-toggle-name="presenter_category_id" data-toggle="buttons-radio">
<%#categorias.each do |x| %>
<button value="<%= x.Id %>" type="button" class="btn" data-age-from="<%= x.FromAge %>" data-age-to="<%= x.ToAge %>"><%= x.Name %></button>
<%end %>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:category].join(", ")%></span>
<% end %>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary"><%= t '.save' %></button>
</div>
<%end%>
_detatails_fields
<%= f.object.errors.inspect %>
<%= f.fields_for :person do |p| %>
<%= render 'person_fields', :f => p %>
<% end %>
_person_fields
<%= f.hidden_field :id %>
<% has_error = f.object.errors.has_key? :CDNI %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :CDNI, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-book"></i></span>
<%= f.text_field :CDNI, :class => 'input' %>
<div class="add-on" id="document_loader"><%= image_tag '6-0.gif' %></div>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:CDNI].join(", ")%></span>
<% end %>
</div>
</div>
<% has_error = f.object.errors.has_key? :DFECHANACIMIENTO %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :DFECHANACIMIENTO, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-calendar"></i></span>
<%= f.text_field :DFECHANACIMIENTO, :class=>'input' %>
<span id="person_age" class="add-on"></span>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:DFECHANACIMIENTO].join(", ")%></span>
<% end %>
</div>
</div>
<% has_error = f.object.errors.has_key? :CNOMBRES %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :CNOMBRES, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-user"></i></span>
<%= f.text_field :CNOMBRES,:class=>'input' %>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:CNOMBRES].join(", ")%></span>
<% end %>
</div>
</div>
<% has_error = f.object.errors.has_key? :CAPELLIDO %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :CAPELLIDO, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-user"></i></span>
<%= f.text_field :CAPELLIDO,:class=>'input' %>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:CAPELLIDO].join(", ")%></span>
<% end %>
</div>
</div>
<div class="control-group">
<%= f.label :CTELEFONO, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-certificate"></i></span>
<%= f.text_field :CTELEFONO,:class=>'input' %>
</div>
</div>
</div>
<% has_error = f.object.errors.has_key? :CSEXO %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :CSEXO, :class=> 'control-label' %>
<div class="controls">
<%= f.hidden_field :CSEXO %>
<div class="btn-group" data-toggle-name="presenter_sex" data-toggle="buttons-radio">
<button type="button" class="btn" value="M"><%= t '.masculine' %></button>
<button type="button" class="btn" value="F"><%= t '.femenine' %></button>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:CSEXO].join(", ")%></span>
<% end %>
</div>
</div>
<% has_error = f.object.errors.has_key? :CCIUDADRESIDENCIA %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :CCIUDADRESIDENCIA, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-map-marker"></i></span>
<%= f.text_field :CCIUDADRESIDENCIA,:class=>'input' %>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:CCIUDADRESIDENCIA].join(", ")%></span>
<% end %>
</div>
</div>
And finally the controller
class RegistrationController < ApplicationController
def index
date = "20120729"
id = 1
#id = params[:event_id] unless params[:event_id].nil?
#date = params[:event_date] unless params[:event_date].nil?
#event = Event.find(date,id)
#groups = Group.all
#categorias = Category.where("DiaActividad = ? and TorneoId = ?", date, id)
#registration = Registration.new
#registration.registrationDetails.build( :person => Person.new)
end
def save
#registration = Registration.new(params[:registration])
if #registration.save
redirect_to :controller => 'home'
else
date = params[:event_date]
id = params[:event_id]
#event = Event.find(date,id)
#groups = Group.all
#categorias = Category.where("DiaActividad = ? and TorneoId = ?", date, id)
render :action => 'index'
end
end
end
What is happening? well first of all, the changes on any field are not saved, and the validations are not displayed. When i submit the form, it returns to the same page, and seems the form has errors but no one is displayed, and the data is lost.
Hope you can help me.
Thanks in advance
Well, I don´t Know why but I solved using resources.
In my routes.rb file
resources :registrations
Before I have something like this.
match 'registration/(:event_date)/(:event_id)' => 'registration#index'
match 'registration/save' => 'registration#save'
I think the problem was my custom routes. But i really don`t know.

Resources