Issue in Form Validation - Ruby on Rails - javascript

I have included validation for my sign up page, but when I load the sign-up page
Error appears. It should show errors after clicking submit button
What i need to do?
My sign-up page
<% if !flash[:notice].blank? %>
<div class="notice">
<%= flash[:notice] %>
</div>
<% end %>
<%= form_for #user,validate: true do |f| %>
<% if !#user.valid? %>
<% if #user.errors.any? %>
<ul class="Signup_Errors">
<% for message_error in #user.errors.full_messages %>
<li>* <%= message_error %></li>
<% end %>
</ul>
<% end %>
<% end %>
<%= f.label("Name:") %>
<%= f.text_field(:user_name, class: "form-control") %></br>
<%= f.label("Email Address:") %>
<%= f.text_field(:email_id, class: "form-control") %></br>
<%= f.label("Password:") %>
<%= f.password_field(:password, class: "form-control") %></br>
<%= f.label("Confirm Password:") %>
<%= f.password_field(:password_confirmation, class: "form-control") %></br>
<%= f.submit("Register",class: "btn btn-primary") %>
<a class="btn btn-primary" style="margin-left:20px" href="/login" >Login</a>
<% end %>
My model where I have included my validations
User.rb
class User < ApplicationRecord
has_many :reviews
has_secure_password
EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :user_name, :presence => true, :on => :create, :uniqueness => true, :length => { :in => 3..20 }
validates :email_id, :presence => true, :on => :create, :uniqueness => true, :format => EMAIL_REGEX
validates :password, :presence => true, :on => :create, :confirmation => true #password_confirmation attr
validates :password_confirmation, :presence => true
end
Controller
def new
puts "****Inside New Method******"
#user = User.new
end
def create
puts "****Inside create Method******"
#user = User.new(user_params)
puts #user.user_name
if #user.save
puts "** USER DETAILS SAVED SUCCESSFULLY****"
flash[:notice] = "Registration successful, please login"
flash[:color] = "valid";
redirect_to "/login"
else
flash[:notice] = "Invalid Form"
flash[:color] = "invalid"
end
end
When I load the page, Error appears before clicking the submit button
I have included :on => :create but it doesn't work
please help!!

if !#user.valid? on the form might be causing this. This is not necesarry, since you are only checking if the record is valid in the controller, just before saving your record.
You should also add render :new when the record could not be saved, otherwise you get a view missing error.

Open rails console and try to manually create the user. Is it create or not?
eg:
user = User.new(username: "test", email_id: "test#test.com", password: ...)
and check the validation by using
user.valid!
you will get the error message if validation fails. If no error then save it
user.save!

Related

Rails: Using remote: true to stop page refresh

I have a projects/show.html.erb page. A project has_many project_messages and from the projects/show.html.erb page, a user can create a new project_message successfully, however, when the new project_message is created through a _formpartial, the page refreshes.
I want to use :remote => true to add project_messages to the project without having to refresh the page.
Please see the code I used below. This does not work and the page still refreshes. I am new to rails so any help would be greatly appreciated.
Please see the code for each file below
In projects/show.html.erbto display the project_message and create a new project_message, I have the following code which is successful:
<div class="au-chat au-chat--border">
<div class="au-message-list">
<% #project.project_messages.each do |project_message| %>
<%= render partial: 'project_messages/project_message', locals: { project_message: project_message } %>
<% end %><br>
</div>
<div class="au-chat-textfield">,
<%= render partial: 'project_messages/form', locals: { project_message: #project_message } %>
</div>
</div>
In the project_messages_controller.rb file the create method is as follows, I have added format.js { }
def create
#project_message = ProjectMessage.new(project_message_params)
#project_message.user_id = current_user.id if current_user
#project_message.project_id = current_user.team.project_id if current_user
respond_to do |format|
if #project_message.save
format.html { redirect_to #project_message.project }
format.json { render :show, status: :created, location: #project_message }
format.js { }
else
format.html { render :new }
format.json { render json: #project_message.errors, status: :unprocessable_entity }
end
end
end
The project_message _form partial then includes the :remote => true
<%= form_with(model: project_message, local: true, :remote => true) do |form| %>
<% if project_message.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(project_message.errors.count, "error") %> prohibited this project_message from being saved:</h2>
<ul>
<% project_message.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form.text_field :pMessage, id: :project_message_pMessage, :class => 'au-input au-input--full au-input--h65', placeholder: 'Type a message' %>
<div class="actions" >
<%= form.submit "Send" %>
</div>
<% end %>
I then created a new create.js.erb file in views/project_messages/create.js.erb and added the following code:
# confirm file called
console.log('create.js.erb file');
# add new comment to end of comments section
$("#project_message").append("<%= j render(#project_message) %>");
With the code above, the page still refreshes.
When I remove local: true from the project_message _form partial, it does not refresh and creates the model but the projects/show.html.erb view is not updated!
I used the following link here and also other posts on stackoverflow
respond_to do |format|
format.js { render 'project_messages/create.js'}
end
it seems you are using Rails 5
remove remote: true and local: true from your code
read about this in here
and make sure that you a html element with id = project_message
your code is $("#project_message").append("<%= j render(#project_message) %>");
so check your HTML code , is there any element with ID like that
you can use traditional form_for http://guides.rubyonrails.org/working_with_javascript_in_rails.html#remote-elements
update below code in your views
<%= form_for project_message, :remote => true do |form| %>
and make sure that you a html element with id like <div class="au-message-list" id="project_message">

Rails / Ajax - update action for comments partial not working

I'm building an events app using Rails 5.0 and have comments as a nested resource. Users can create and destroy comments, I'm trying to implement the edit/update function using Ajax/ remote: true so they can update a comment on the same page but it's not working. When I click on the edit link nothing happens. Here's the relevant code -
comments_controller.rb
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
def create
#event = Event.find(params[:event_id])
#comment = #event.comments.create(comment_params)
#comment.user_id = current_user.id
if #comment.save
redirect_to #event
else
render 'new'
end
end
# GET /comments/1/edit
def edit
#event = #comment.event
#comment = #event.comments.find(params[:id])
respond_to do |format|
format.html { render :edit }
format.js {}
end
end
def show
end
def update
if #comment.update(comment_params)
redirect_to #event, notice: "Comment was successfully updated!"
else
render 'edit'
end
respond_to do |f|
format.html { redirect_to #event, notice: "Comment Successfully updated!" }
format.js # render 'comments/update.js.erb'
end
end
def destroy
#event = Event.find(params[:event_id])
#comment = #event.comments.find(params[:id])
#comment.destroy
redirect_to event_path(#event)
end
private
def set_comment
#comment = Comment.find(params[:id])
end
def comment_params
params.require(:comment).permit(:name, :body)
end
end
_comment.html.erb
<div class="comment clearfix">
<div class="comment_content">
<div id="comments" class="comment">
<p id="comment_name"><strong><%= #comment.name %></strong></p>
<p id="comment_body"><%= #comment.body %></p>
</div>
<p><%= link_to 'Edit', edit_event_comment_path(comment.event), id: "comments", remote: true %></p>
<p><%= link_to 'Delete', comment.event,
method: :delete,
class: "button",
data: { confirm: 'Are you sure?' } %></p>
</div>
</div>
update.js.erb
$('#comments').append("<%= j render #comment %>");
edit.js.erb
$('#comments').html("<%= j render 'form' %>");
_form.html.erb
<%= simple_form_for([#event, #comment], remote: true) do |f| %>
<%= f.label :comment %><br>
<%= f.text_area :body %><br>
<br>
<%= f.button :submit, label: 'Add Comment', class: "btn btn-primary" %>
<% end %>
I've never implemented this action before using Ajax so I'm probably making a few schoolboy errors here. Any assistance appreciated.
You are calling edit method on controller with this
<%= link_to 'Edit', [comment.event, comment], id: "comment", remote: true %>
And you have no edit.js.erb
For updating your comment, you would have to create a form with it's action url pointing to your update method, and marking it as remote true. Then when you submit, it will reach update directly, there is no need to pass through edit method.
There is a method for creating forms with ajax option as default called form_with, you can check it's guide and documentation here:
http://guides.rubyonrails.org/working_with_javascript_in_rails.html#form-with
Updating answer after your question update
Your form would need to become something like this
<%= simple_form_for :comment, :url => "/events/#{comment.event_id}/comments/#{comment.id}", :method => :put do |f| %>
<%= f.label :comment %><br>
<%= f.text_area :body %><br>
<br>
<%= f.button :submit, label: 'Add Comment', class: "btn btn-primary" %>
<% end %>

undefined method `events' for nil:NilClass

I was working with nested attributes, everything seemed to be fine until when I submitted my information and I got this error. It says it is in my EventsController file:
class EventsController < ApplicationController
def new
#event = Event.new
#event.songs.build
end
def index
#songs = Song.all
end
def show
#event = Event.find(params[:id])
#songs = #event.songs.paginate(page: params[:page])
end
def create
#event = current_user.events.build(event_params)
if #event.save
flash[:success] = "Event Created!"
redirect_to user_path(#event.user)
else
render 'welcome#index'
end
end
def destroy
end
private
def event_params
params.require(:event).permit(:name, :partycode, song_attributes: [:event_id, :artist, :title, :genre, :partycode])
end
end
Here is my new.html.erb file in my songs view(handles song submission based on selected event)
<br>
<br>
<div class ="container">
<div class="jumbotron">
<%= form_for Event.new do |f| %>
<h3>Enter a song:</h3>
<%= f.fields_for :songs, Song.new do |song_form| %>
<%= song_form.collection_select(:event_id, Event.all, :id, :name) %>
<%= song_form.text_field :artist, placeholder: "Artist" %>
<%= song_form.text_field :title, placeholder: "Title" %>
<%= song_form.text_field :genre, placeholder: "Genre" %>
<% end %>
<%= link_to_add_fields "Add Song", f, :songs %>
<%= f.text_field :partycode %>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
</div>
</div>
The link_to_add_fields method is defined in my ApplicationHelper.rb file:
module ApplicationHelper
def link_to_add_fields(name, f, association)
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render("songs_fields", f: builder)
end
link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
end
end
current_user is defined in Session_helper.rb file:
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
def createEvent(event)
session[:event_id] = event.id
end
# Returns the current logged-in user (if any).
def current_user
#current_user ||= User.find_by(id: session[:user_id])
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
def log_out
session.delete(:user_id)
#current_user = nil
end
end
Finally, here is my songs_fields file that generates fields only when a user clicks a link that says 'Add songs'
<fieldset>
<%= f.text_field :artist, placeholder: "Artist" %>
<%= f.text_field :title, placeholder: "Title" %>
<%= f.text_field :genre, placeholder: "Genre" %>
</fieldset>
I feel as though this is the last portion before I get everything in my app to work! So help on this would be tremendous :D
You answered your own question... if you're not logged in, current_user will be nil so you will get this error.
Option 1 (ugly): change your logic so current_user.events doesn't get called if current_user is nil, and just go straight to the render
Option 2 (better): use a before_action statement to force current_user to be set before the action is run. Depends on what you're using to authenticate, but with Devise it would look like this:
class EventsController < ApplicationController
before_action :authenticate_user!
I think maybe:
class EventsController < ApplicationController
before_action :log_in(user)
might do it for you.

Completely Stuck on AJAX Form Submission With Stripe

I am so frustrated. I'm working with Stripe to create a form submission system for payments. Basically, the form makes an AJAX call to Stripe, which gives me a token on success, which I then use to resubmit the form, also through AJAX. If the form is successful, it redirects to a new page, if not, it populates the form with error messages without re-navigation. Here's my form:
<%= form_for([#issue, #issue_order]) do |f| %>
<% if #issue_order.errors.any? %>
<div class="error_messages">
<h2><%= pluralize(#issue_order.errors.count, "error") %> occurred. </h2>
<ul>
<% #issue_order.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<% f.hidden_field :issue_id %>
<%= f.hidden_field :stripe_card_token %>
<div class="field">
<%= f.label :email %>
<%= f.text_field :email %>
</div>
<div class="field">
<%= label_tag :card_number, "Credit Card Number " %>
<%= text_field_tag :card_number, nil, name: nil %>
</div>
<div class="field">
<%= label_tag :card_code, "Security Code on Card (CVV) " %>
<%= text_field_tag :card_code, nil, name: nil %>
</div>
<div class="field">
<%= label_tag :card_month, "Card Expiration " %>
<%= select_month nil, {add_month_numbers_true: true}, {name: nil, id: "card_month"} %>
<%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year + 15}, {name: nil, id: "card_year"} %>
</div>
<div id="stripe_error"></div>
<div class="actions"><%= f.submit "Purchase Issue", id: "submit_issue_order" %></div>
<% end %>
<div class="errors"></div>
Here is the javascript that handles the form and sets up the stripe information:
var issueOrder;
$(function() {
Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'));
issueOrder.setupForm();
});
var issueOrder = {
setupForm: function() {
$('#new_issue_order').submit(function(e) {
e.preventDefault();
$('#submit_issue_order').attr('disabled', true);
issueOrder.processCard();
return false;
});
},
processCard: function() {
var card;
card = {
number: $('#card_number').val(),
cvc: $('#card_code').val(),
expMonth: $('#card_month').val(),
expYear: $('#card_year').val()
};
Stripe.createToken(card, issueOrder.handleStripeResponse)
},
handleStripeResponse: function(status, response) {
if (status == 200) {
$('#issue_order_stripe_card_token').val(response.id);
// $('#new_issue_order')[0].submit();
$.ajax({
type: "POST",
url: $('#new_issue_order').attr('action'),
data: { "issue_order": {
"stripe_card_token": $('#issue_order_stripe_card_token').val(),
"email": $('issue_order_email').val(),
},
"issue_id": $('#issue_order_issue_id').val()
},
dataType: "script"
}, issueOrder.processOrder);
}
else {
$('#stripe_error').text(response.error.message);
$('input[type=submit]').attr('disabled', false)
}
}
And here is my controller:
def create
charge = Stripe::Charge.create(
:amount => 400,
:currency => "usd",
:card => params['issue_order']['stripe_card_token']
)
if charge['paid'] == true
#issue_order = IssueOrder.new(email: params['issue_order']['email'], issue_id: params['issue_id'])
if #issue_order.save
#pdf_token = #issue_order.pdf_token
PdfMailer.pdf_email(params['issue_order']['email'], #issue_order).deliver
else·
flash[:error] = []
flash[:error].push("Your card was charged, but sadly we were unable to create·
a record in the database. Please contact us for your copy of the issue.")
respond_to do |format|
format.js
end
end
else
# run checks for errors and return error messages
flash[:error] = []
flash[:error].push("There was an error in processing your payment.")
render :json => {success: false}
end
end
Typical stripe setup stuff. Works fine when the stripe order is successfully processed. Well, it did before I hand-rolled the AJAX call, I'm assuming it'd be fine if I threw a respond_to |format| in the success case in the controller that redirected to the success page. However, for the error cases, my controller renders create.js.erb, which looks like this:
console.log('yo');
$('.errors').empty();
errors = xhr.getResponseHeader('X-Flash-Error').split(',');
<% flash[:error].each do |error| %>
$('.errors').append($('<p>' + <%= error %> + '</p>'));
<% end %>
setTimeout(function() {
$('.errors').empty();
}, 3500);
The controller clearly reaches the file and renders it, as evidenced by the logs:
Started POST "/issues/1/issue_orders" for 127.0.0.1 at 2013-11-12 23:33:17 -0500
Processing by IssueOrdersController#create as JS
Parameters: {"issue_order"=>{"stripe_card_token"=>"tok_102vmu2pSkyWUgPAToj334Oa"}, "issue_id"=>"1"}
(0.4ms) BEGIN
(0.4ms) ROLLBACK
Rendered issue_orders/create.js.erb (0.1ms)
["Your card was charged, but sadly we were unable to create \n a record in the database. Please contact us for your copy of the issue."]
Completed 200 OK in 1363ms (Views: 3.9ms | ActiveRecord: 0.8ms)
But NOTHING happens on my page, including the console log! If I don't hand roll the AJAX and use remote: true, it gets even worse -- it recognizes my submit() call as HTML and doesn't know what to do with the format, rendering an Unknown Format error.
Help!

Routing error that appears to have something to do with partials and/or forms

In a Rails 3 application, I have a "table" partial that contains a data entry form table, plus a separate smaller form (mostly hidden fields) below it to clear the table data. I have a third form underneath the partial to add a new column to the table contained in the partial. The page loads fine. The small form to clear the table data works, and refreshes the partial as it is supposed to. BUT, When I submit the add-new-column form, I get this routing error:
ActionView::Template::Error (No route matches {:controller=>"outcome_results", :action=>"clear_table"}):
70: </table>
71: <%= submit_tag "Save" %>
72: <% end %>
73: <%= form_tag url_for(:controller => 'outcome_results', :action => 'clear_table'), :id => "clear_data_table_link", :remote => true do %>
74: <%= hidden_field_tag "subgroup_id", subgroup_id %>
75: <%= hidden_field_tag "outcome_id", #selected_outcome_object.id %>
76: <%= hidden_field_tag "timepoint_id", timepoint_id %>
app/views/outcome_results/_table.html.erb:73:in `_app_views_outcome_results__table_html_erb__204353865_18893424_435027370'
app/controllers/outcome_columns_controller.rb:36:in `block (3 levels) in create'
app/controllers/outcome_columns_controller.rb:35:in `block (2 levels) in create'
app/controllers/outcome_columns_controller.rb:33:in `create'
Line 72 is the end tag of the first (table/data entry) form.
Line 73 is the form tag for my clear-table-data form which works fine on its own - no routing errors there.
My routes.rb is crazy long but contains this line:
match 'projects/:project_id/studies/:study_id/clear_table' => 'outcome_results#clear_table'
The add-new-column form looks like this:
<div id="outcome_column_validation_message"></div>
<%= form_for #outcome_column, :action => :create, :remote => true, :id=>"outcome_columns_form" do |f| %>
<%= hidden_field_tag "outcome_id", !#selected_outcome_object.nil? ? #selected_outcome_object.id : nil %>
<%= hidden_field_tag "subgroup_id", !#selected_timepoint.nil? ? #selected_timepoint : 0 %>
<%= hidden_field_tag "timepoint_id", !#selected_subgroup.nil? ? #selected_subgroup : 0 %>
<div class="field">
Custom Column Title: <%= f.text_field :name %> Description: <%= f.text_field :description %> <%= f.submit "Add Custom Column" %>
<% end %>
and the format section of the "create" action in the "outcome_column" controller looks like this:
respond_to do |format|
format.js {
render :update do |page|
page.replace_html 'outcome_results_table', :partial => 'outcome_results/table'
page['outcome_columns_form'].reset
page.replace_html 'outcome_column_validation_message', ""
end
}
end
I can post more code if it would help... anyone have any ideas about this routing error?
Thanks in advance.
The route would take two arguments: a project_id and a study_id. This is not matching the route because you have not passed through these two parameters to the url_for in your form_tag.

Categories