I am working in rails 2, I have a form containing data of two models, In one model I am validating fields and entering error using self.errors.add_to_base , but this is not displaying error on form and submitting that request successfully.
This is my Model validation\
validate :checkPunchingEntries
def checkPunchingEntries
if self.punch_in_time.blank? && self.punch_out_time.blank?
self.errors.add_to_base("Both 'Punch in' and 'Punch out' time can not be blank")
end
end
This is my Form
<% form_tag '/punching_requests/create', :method => :post, :class=>"punching_request_form" do %>
<% #punching_request.errors.full_messages.each do |msg| %>
<p class="error"><%=msg%></p>
<% end %>
<p>
<label>Date </label>
<%= text_field_tag 'date'%> <%= calendar_for("date") %>
</p>
<p>
<label> </label>
<input type="checkbox" onclick="punch_in_toggle()">Punch In</input>
<input type="checkbox" onclick="punch_out_toggle()">Punch Out</input>
</p>
<div id="punch_in">
<p>
<label>Punch In Time </label>
<%= text_field_tag 'punch_in_time'%>
</p>
</div>
<div id="punch_out">
<p>
<label>Punch Out Time </label>
<%= text_field_tag 'punch_out_time'%>
</p>
</div>
<p>
<label>Assign To</label>
<%= select_tag(:approved_by, options_from_collection_for_select(#human_resource_persons, "id", "login")) %>
</p>
<p>
<label>Reason </label>
<%=text_area_tag 'reason'%>
</p>
<p class="actions"><label></label><%= submit_tag 'Save' %></p>
<% end %>
It comes into validation, but error is not shown on validation fails.
Have you tried the IRB console? If not, take a look what is going on there, just to be sure, that #punching_request.errors contains something.
try this
def checkPunchingEntries
if self.punch_in_time.blank? && self.punch_out_time.blank?
errors[:base]<< "Both 'Punch in' and 'Punch out' time can not be blank"
end
end
and use form_for and #punching_request
for example
# in your controller
def new
#punching_request = PunchingRequest.new
end
def create
...
...
end
your form look like in your new.html.erb
form_for(#punching_request)
...
...
end
In this you're generating the form using form_tag and the errors you're expecting would be stored in the form builder,form_for.
Instead of form_tag use form_for(#punching_request). This should do the trick.
Related
Im submitting my form with checkboxes via Jquery with remote true but its not working. Its keeps rendering the html format in the controller and i can work out why.
Here is my submit button and form:
<%= button_to "Read sel", root_path, class: "btn btn-info btn-sm padlr", id: "notification-submit" %>
<%= form_tag read_selected_notifications_path, :authenticity_token => true, remote: true ,id: "notification-form" do %>
<% #notifications.each do |x| %>
<div class="notification-body flerowspb">
<div class="flerowspb" style="width:80%">
<div class="notif-check flecolcen">
<%= check_box_tag "read_notif[]", value="#{x.id}" %>
</div>
<div class="notif-details ">
<div class="notif-time flerowspb">
<% if !x.viewed %>
<span class="glow"> New <%= x.notification_type.capitalize %></span>
<% else %>
<span><span class="text-grey"> New <%= x.notification_type.capitalize %></span></span>
<% end %>
<span class="text-grey font-small"> <%= time_ago_in_words(x.created_at) %> ago</span>
</div>
<div class="notif-body font-medium text-grey">
<span class="text-blue"><%= link_to x.sender.username, profile_path(x.sender) %> </span> <%= x.title %> <br>
Click <span class="text-blue"><%= link_to "Here", entry_path(x.entry_id, notification_id: x.id) %> </span> to view it
</div>
</div>
</div>
<div class="notif-image">
<%= image_tag x.entry.image.small_thumb %>
</div>
</div>
<% end %>
<% end %>
So there is no actual submit button for the form as i want the button above the form not below it like this,
I understand i have to add :authenticity_token => true as rails doesnt add this to form_tag with remote: true
Here is my controller:
def read_selected
Notification.read_selected(current_user.id, params[:read_notif])
respond_to do |format|
format.html{
flash[:success] = "Selected notifications marked as read"
redirect_to notifications_path
}
format.js{
render 'notifications/jserb/read_selected'
}
end
end
Here is the js code:
$(document).on('turbolinks:load', function(){
if (window.location.href.match(/\/notifications/)) {
$('#notification-submit').on('click', function(e){
console.log('oisdjfilds');
e.preventDefault();
$('#notification-form').submit();
});
}
});
EDIT: I added in a submit button at the bottom of the form and it works as it should do, So it something to do with the way i'm submitting the form
I assume you're using Rails 5, since there is such an inconsistency in its behavior. Please, check out the issue
As far as I understand the quick solution for your problem is going to be:
Get the form HTML element:
form = document.getElementById('notification-form');
or
form = $('#notification-form')[0]
And then fire Rails submit:
Rails.fire(form, 'submit');
or
form.dispatchEvent(new Event('submit', {bubbles: true}));
I have Stripe integrated with Stripe Gem and I can successfully create charges and a Stripe user; I just can't get the two to have an association. If I associate the :source => params[:stripeToken] the charge goes through, but if I associate it with my user model :source => current_user.stripe_customer, I get a No such token: cus_BX2RXGoOVkpvhL error.
Here are my request parameters when associating with my user model.
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"/KI7rzkJsM2uXIynoZkWKa1L+kNgyVcw+UsqfPNOnLYO3t4vfL+R7Yb4XhonyhwTbqlyWTtgYjey71ZroSmoRA==",
"charge"=>"2200",
"stripeToken"=>"tok_1B9yneHbiQgBeZWGq78mXM2l",
"card_brand"=>"Visa",
"card_exp_month"=>"4",
"card_exp_year"=>"2024",
"card_last4"=>"4242"}
views/donations/show.html.erb
...
<%= link_to 'Confirm Donation', new_checkout_path(charge: #donation.amount), class: 'btn btn-primary' %>
...
views/checkouts/new.html.erb
<section>
<h1>Secure Payment</h1>
<div class="pages-content">
<% if current_user.card_last4? %>
<%= form_tag checkout_path, id: 'existing-card' do %>
<p>Pay with existing card:</p>
<div><strong>Card on file:</strong>
<%= current_user.card_brand %> (**** **** **** <%= current_user.card_last4 %>)
</div>
<div><strong>Expiration:</strong> <%= current_user.card_exp_month %> / <%= current_user.card_exp_year %></div>
<p>or <%= link_to 'add a new card', '#', class: 'show-card-form' %></p>
<%= hidden_field_tag :charge, params[:charge] %>
<input type="submit" class="btn btn-default" value="Submit Payment">
<% end %>
<% end %>
<%= form_tag checkout_path, id: 'payment-form', style: (current_user.card_last4? ? 'display:none' : nil) do %>
<div class="stripe-wrapper">
<div class="form-row">
<label for="card-element">
Enter Your Credit or Debit Card
</label>
<div id="card-element">
<!-- a Stripe Element will be inserted here. -->
</div>
<%= hidden_field_tag :charge, params[:charge] %>
<!-- Used to display Element errors -->
<div id="card-errors" role="alert"></div>
</div>
<button>Submit</button>
</div>
<% end %>
</div>
</section>
models/user.rb
class User < ApplicationRecord
...
def stripe_customer
if stripe_id?
Stripe::Customer.retrieve(stripe_id)
else
stripe_customer = Stripe::Customer.create(email: email)
update(stripe_id: stripe_customer.id)
stripe_customer
end
end
You need to do this instead, if you're charging the Customer by ID:
:customer => current_user.stripe_customer
I had a similar problem once and i remember that it was because my partner was using a different [Publishable key] on Testing mode, So i gave him mine and it worked, I would like you to make sure that the user is already exists on stripe.
I hope this help you.
I have a form that looks like this -
<%= form_for #photo,:html=>{:multipart=>true} do |f| -%>
<div>
<%= f.file_field :photo %>
<%= f.submit "Upload", :disable_with => 'Uploading...' %>
</div>
<%= #photo.errors[:photo].each do |attr,msg| %>
<span class="form-error"><%= msg %></span>
<% end %>
<% end -%>
My model has the following line
validates_presence_of :photo, :message => "Choose a file to upload"
For some reason the error message is rendering outside of containing span. The rendered HTML looks like this -
<form ..some attributes..><some hidden divs and inputs />
<div class="field_with_errors"><input type="file" name="photo[photo]" id="photo_photo"></div>
<input type="submit" value="Upload" name="commit" id="photo_submit" data-disable-with="Uploading...">
<span class="form-error"></span>
Choose a file to upload
</form>
I'm very new to rails, but this seems odd to me.
Why is my message outside of it's container?
Thanks.
Shouldn't this NOT have an equal sign (you like my double negative there)?
<%= #photo.errors[:photo].each do |attr,msg| %>
/ \
|
|
In other words, it should be:
<% #photo.errors[:photo].each do |attr,msg| %>
I've made this typo about a hundred times, and have finally got out of the habit of doing it. I'll bet that is part of the issue.
Your form_for needs and equal sign, because it outputs HTML into your view. The loop itself does not, because it is just a loop.
On my site, the user can watch his profile. In his profile he can have a look at his data (i.e. signature).
Now I want my users being able to edit this data while watching it.
So I coded the following in my view:
<div id="profile-signature">
<p>
<b>Signature:</b>
<%=h #user.signature %>
</p>
<%= form_remote_tag(:update => "signature",:url => { :action => :update_signature }) %>
<%= text_area(:signature,:class=>"form-textarea") %>
<%= submit_tag "Save Signature" %>
</div>
in my user controller, I created a new action update_signature
def update_signature
puts 'in function!'
#user = current_user
puts #user.login
puts params[:signature]
#user.signature = params[:signature]
#user.save
puts 'saved'
end
Now, submitting the form, puts params[:signature] will output: classform-textareasfsffsfs
where sfsffsfs is the text I entered.
Reloading and my page and output the signature on page (<%=h #user.signature %>), I get:
"--- !map:HashWithIndifferentAccess classform-textarea: sfsffsfs "
Why do I get this strange string instead of just sfsffsfs (in this case)?
What to do, to update the data (<%=h #user.signature %>) automatic without page reload?
Use text_area_tag for getting the text_area field values . With reloading the page there is a mismatch in the div id it should be signature not profile-signature .
<div id="profile-signature">
<p>
<b>Signature:</b>
<%=h #user.signature %>
</p>
<%= form_remote_tag(:update => "signature",:url => { :action => :update_signature }) %>
<%= text_area(:signature,:class=>"form-textarea") %>
<%= submit_tag "Save Signature" %>
</div>
Make the following changes
<div id="signature">
<p>
<b>Signature:</b>
<%=h #user.signature %>
</p>
<%= form_remote_tag(:update => "signature",:url => { :action => :update_signature }) %>
<%= text_area_tag(:signature,:class=>"form-textarea") %>
<%= submit_tag "Save Signature" %>
</div>
Hope this helps !
It looks like your text_area call isn't quite right, looking at the docs it should be like this:
text_area(object_name, method, options = {})
so your css class is being set as the method, instead you should use text_area_tag:
<%= text_area_tag(:signature, #user.signature, :class=>"form-textarea") %>
Then the correct value (the text in the text area) should be submitted as the params you're expecting.
I have this method to post the value to the "/store/add_to_cart"
<form action = "/store/add_to_cart" method="post">
<% for product in #products -%>
<div class = "entry">
<%= product.title %>
<%= product.price %>
<p>
</div>
<% end %>
<%= select( "payment", "id", { "Visa" => "1", "Mastercard" => "2"}) %>
<%= submit_tag 'Make Order' %>
</form>
In the /store/add_to_cart.html.erb, I created :
<%= params.length %>
<% for i in params%>
<%=i%>
<br/>
<% end %>
But I get this error:
ActionController::InvalidAuthenticityToken in StoreController#add_to_cart
What's happen? but after I change it to the get method, I can get all the params, wt's happen?
You are not using rails form_for helper to generate the <form> HTML markup, what this method does in addition is to add a hidden input field that is used to prevent CSRF attacks.
You have three options:
Use the form_for, form_tag... helper
Include the hidden input yourself
Disable the CSRF support