I have added Stripe payment to my app to handle registration payments for events, the form is on the event show page so the method is in the events controller but I have created a registration model. My issue is trying to get the price of the event into the save_with_payment method inside the registration model(total_price).
Any ideas? I have tried attr_accessible :price but with no luck.
Event Controller
def show
#event = Event.where(:slug => params[:slug]).first
#registration = Registration.new
end
def payment
#registration = Registration.new(params[:registration])
if #registration.save_with_payment
RegistrationMailer.admin(#registration, #event).deliver
RegistrationMailer.delegate(#registration, #event).deliver
redirect_to root_path
flash[:success] = "Thank you for registering for <% #event.title %>"
else
redirect_to root_path
flash[:error] = "We're sorry, something went wrong"
end
end
Registration Model
def save_with_payment
if valid?
charge = Stripe::Charge.create({
amount: total_price, ##I can declare a integer here instead of a method and it works
currency: "gbp",
card: stripe_card_token,
description: email })
save
end
rescue Stripe::CardError => e
end
def total_price
#event.price = price
price
end
Routes
match 'registration' => 'events#show', :via => :get
match 'registration' => 'events#payment', :via => :post
View
<%= simple_form_for [#registration], :method => :post, :url => registration_path do |f| %>
<%= f.input :first_name %>
<%= f.input :last_name %>
<%= f.input :email %>
<%= f.input :job_title %>
<%= f.input :company %>
<%= f.input :stripe_card_token, as: :hidden %>
<div class="input card_number">
<label for="card_number">Card number</label>
<%= text_field_tag :card_number %>
</div>
<div class="input card_cvc">
<label for="card_code">Security code (CVC)</label>
<%= text_field_tag :card_cvc %>
</div>
<div class="input card_dates">
<label>Card expiration date</label>
<%= select_month nil, { add_month_number: true }, { id: "card_month"} %>
<%= select_year nil, { add_year: Date.today.year, end_year: Date.today.year + 15 }, { id: "card_year"} %>
</div>
<%= f.button :submit, "Register", class: "button" %>
If I got everything right, here:
def show
#event = Event.where(:slug => params[:slug]).first
#registration = Registration.new
end
is controller action with view, containing form.
Registration should belong to event, I suppose, through :has_one
Then your registration model needs event_id integer column. As you declared #event in show, append you registration form with
<%= f.input :event_id, as: :hidden, value: #event.id %>
After that you can find #event in payment method by:
#event=Event.find(params[:registration][params[:event_id]].to_i)
This is basic example, I don't actually know, what is event in your app, may be there is better attribute which you can pass.
After that you can pass #event.price as argument to model method:
def save_with_payment(total_price)
if valid?
charge = Stripe::Charge.create({
amount: total_price,
#other code
Related
I would like to use ruby mail_form and Heroku Sendgrid to allow users to send me an email. I have set up the following Contact class in apps/models/contact.rb
class Contact < MailForm::Base
attribute name, :validate => true
attribute email, :validate => /\A([\w\.%\+\-]+)#([\w\-]+\.)+([\w]{2,})\z/i
attribute message, :validate => true
attribute nickname,:captcha => true
def headers
{
:subject => "Contact Form",
:to => "example#email.com",
:from => %("#{name}" <#{email}>)
}
end
end
However, when I visit the page where I have set up my form, I receive the following error message:
undefined local variable or method `email' for Contact:Class
Commenting out the email attribute defined in my Contact class produces similar errors in subsequent attributes message: and nickname:
Below is my Contacts controller, contacts_controller.rb
class ContactsController < ApplicationController
def new
#contact = Contact.new
end
def create
#contact = Contact.new(params[:contact])
#contact.request = request
if #contact.deliver
flash.now[:error] = nil
else
flash.now[:error] = "Oops! There was an error."
render :new
end
end
end
and my form, new.html.erb
<% provide(:title, "Contact") %>
<h1>Contact</h1>
<%= form_for #contact do |f| %>
<%= f.label :name %><br>
<%= f.text_field :name, required: true %>
<br>
<%= f.label :email %><br>
<%= f.text_field :email, required: true %>
<br>
<%= f.label :message %><br>
<%= f.text_area :message, as: :text %>
<div class="hidden">
<%= f.label :nickname %><br>
<%= f.text_field :nickname, hint: "Leave this field blank." %>
</div>
<%= f.submit "Send Message", class: "btn" %>
<% end %>
<ul class="pager">
<li>Previous</li>
</ul>
Any help or suggestions would be greatly appreciated!
You omitted double quotes in the from option.
def headers
{
:subject => "Contact Form",
:to => "example#email.com",
:from => %("#{name}" <#{email}>)
}
end
I want to send multiple invitations at a time using devise-invitable gem.
new.html.erb
<h2>
<%= t "devise.invitations.new.header" %>
</h2>
<%= form_for resource, :as => resource_name, :url => invitation_path(resource_name), :html => {:method => :post} do |f| %>
<%= devise_error_messages! %>
<div>
<% resource.class.invite_key_fields.each do |field| -%>
<p><%= f.label field %><br />
<%= f.email_field field, placeholder: "Invitation email" %></p>
<% end -%>
<%= f.collection_select(:role_id, Role.all, :id, :role_name, :prompt => true) %>
</div>
<p>
<%= f.submit t("devise.invitations.new.submit_button") %>
</p>
<% end %>
my controller:-
class Users::InvitationsController < Devise::InvitationsController
def create
exit
if params[:user][:email]== "" || params[:user][:role_id] == ""
flash[:alert]="Please enter email first and Select any role for invitees"
redirect_to new_user_invitation_path
else
if User.invite!(:email => params[:user][:email], :company_id => current_user.id, :type => 'Employee', :role_id => params[:user][:role_id])
flash[:notice]="Invitation is send successfully."
redirect_to new_user_invitation_path
else
flash[:alert]="Invitation is not send."
redirect_to new_user_invitation_path
end
end
end
end
I think one solution is to pass comma separated emails in invite method but how can I pass it? I really don't know how.
If you have any other solution then please tell me.
Thanks.
i trouble with this problem but finally i got solution to send multiple invitation email at a time.
below i explain my code that how i become possible this.
here is my html view.
new.html.erb
<h2>
<%= t "devise.invitations.new.header" %>
</h2>
<%= form_for resource, :as => resource_name, :url => invitation_path(resource_name), :html => {:method => :post} do |f| %>
<%= devise_error_messages! %>
<div>
<% resource.class.invite_key_fields.each do |field| -%>
<%= f.label field %><br />
<%= f.email_field field, name: "user[email][]", placeholder: "Invitation email", required: true %></p>
<div id="createNewTextbox" >
</div>
<a id="btnLinkCreate" href="#" onClick="create_new();">
+ INVITE MORE
</a>
<% end -%>
</div>
<p>
<%= f.submit t("devise.invitations.new.submit_button") %>
</p>
<% end %>
in this i take one text-box by-default with name : "user[email][]" (it is important because using this rails automatically create email array and send in params whene you submit form )
i also generate dynamic text-box using JavaScript and it will create below div when click on invite more link button :
<div id="createNewTextbox" >
</div>
<a id="btnLinkCreate" href="#" onClick="create_new();">
+ INVITE MORE
</a>
here is my dynamic text-box code of JavaScript.
$('#createNewTextbox').append('<input type="email" id="email'+i+'" name="user[email][]" placeholder="Invitation email" required/>');
now you can see that i give same name to dynamic text-box (name="user[email][]"), so rails automatically create hash array like this:
"user" => { "email" => { "email-1","email-2","email-3"... } }
now this hash array is pass in create method in which we fetch every email from params and give it to invite method to send the invitation.
my controller :-
class Users::InvitationsController < Devise::InvitationsController
def create
params[:user][:email].each do |email|
User.invite!(:email => email)
end
end
end
thats it...
if still you have any query then tell comment me.
Firstly, I would like to describe what I am going to do. So, my application is set of tasks (eg. exercises depend on writing computer program) which user it available to send solutions through form and server will have compiled it and return results of process.
My problem is that I have model Solution which is presented below:
Solution(id: integer, exercise_id: integer, code: string, user_id: integer,
created_at: datetime, updated_at: datetime, language_id: integer)
and exercise_id, user_id, language_id are foreign keys and postgresql return error that it couldn't be null values...
The form which I use to send this information looks like below:
<fieldset style="add">
<legend>Send solution</legend>
<%= form_for [#user, #exercise, #solution], url: exercise_solutions_path, :html => { role: "form" } do |f| %>
<div class="form-group">
<%= f.label "Source code" %>
<br>
<%= f.text_area :code %>
</div>
<div class="form-group">
<%= f.label "Programming language" %>
<br>
<%= f.select(:language_id, available_lang) %>
</div>
<div class="form-group">
<%= f.submit "Send", :class => "btn btn-default" %>
</div>
<% end %>
</fieldset>
Frankly speaking I don't how to include more information such as user.id or exercise.id. Params look like:
#_params
{"utf8"=>"✓", "authenticity_token"=>"abwhTn3KrVneli0pCVccoWHyzlI7cRTFK5Wo7DdYRK+lL4GwZ8jUPqdzn8ZznCHsWTkfDAFS2RP6gTkWuk33iw==", "solution"=>{"code"=>"ds", "language_id"=>"C++"}, "commit"=>"Wyślij", "controller"=>"solutions", "action"=>"create", "exercise_id"=>"1"}
SolutionController
class SolutionsController < ApplicationController
def index
#solutions = Solution.last(20)
end
def new
#solution = Solution.new
end
def create
#solution = Solution.new(solution_params)
if #solution.save
redirect_to #solution
else
render :new
end
end
def edit
#solution = Solution.find(params[:id])
if #solution.update(solution_params)
redirect_to #solution
else
render :edit
end
end
def destroy
end
private
def solution_params
params.require(:solution).permit(:language_id, :code)
end
end
Edit:
<fieldset style="add">
<legend>Send solution</legend>
<%= form_for [#user, #exercise, #solution], url: exercise_solutions_path, :html => { role: "form" } do |f| %>
<div class="form-group">
<%= f.label "Source code" %>
<br>
<%= f.text_area :code %>
</div>
<div class="form-group">
<%= f.label "Programming language" %>
<br>
<%= f.select(:language_id, available_lang) %>
</div>
<div class="form-group">
<%= f.hidden_field :exercise_id, value: #exercise.id %>
<%= f.hidden_field :user_id, value: #user.id %>
<%= f.submit "Send", :class => "btn btn-default" %>
</div>
<% end %>
</fieldset>
You could 1) add hidden_fields in your form to set the missing attributes:
<div class="form-group">
<%= f.hidden_field :exercise_id, value: #exercise.id %>
<%= f.hidden_field :user_id, value: #user.id %>
<%= f.submit "Send", :class => "btn btn-default" %>
</div>
Make sure to add these attributes to the solution_params permitted parameters:
def solution_params
params.require(:solution).permit(:language_id, :code, :exercise_id, :user_id)
end
A better idea would be to manually set the exercise and user in the controller and leave your solution_params as is. That way you're not allowing the exercise and user to be set by mass assignment, which could be spoofed.
So instead do 2) in your controller:
def create
#solution = Solution.new(solution_params)
#solution.exercise_id = params[:exercise_id]
#solution.user_id = params[:user_id]
if #solution.save
redirect_to #solution
else
render :new
end
end
I'm assuming that :exercise_id and :user_id are in the URL. If not add them as hidden_fields as needed (but this time not on the form object):
<%= hidden_field_tag :user_id, #user.id %>
Also remember to actually select a language_id from the dropdown before you submit the form.
I have these forms:
<%= form_for(#user) do |f| %>
<div>
<%= f.number_field :money, :value => #user.money %>
</div>
<% end %>
and
<%= form_for #product, :url => product_path, :html => { :multipart => true } do |f| %>
<div>
<%= f.label :count, 'How Many product?' %><br />
<%= f.number_field :count, :value => "1" %>
</div>
<div>
<%= f.submit('submit') %>
</div>
<% end %>
is there any way to submit this two at once when clicking submit button ? Thanks!
A service object might be a good way to approach this.
class Order
include ActiveModel::Model
attr_accessor :money, :count
def initialize(user=nil, product=nil)
#user = user
#product = product
#money = user.money
#count = 1
end
def persisted?
false
end
def save
// this code needs to save to db
end
end
Bassicaly my problem what to do if i have 3 forms and one submit button.
I want to create a form which sends email to each recipient and then create new record in free_registration_coupons table.
I need validation of email for this form.
Model FreeRegistrationCoupon: recipient_email, token, sender_id
For now i have this:
class FreeRegistrationCouponsController < ApplicationController
def send_invitations
emails = [params[:recipient_email_1], params[:recipient_email_2], params[:recipient_email_3]]
emails.reject!{ |e| e.eql?("") }
if emails.present?
emails.each do |e|
FreeRegistrationCoupon.create(:recipient_email => e, :sender_id => current_user.id)
#MAILER
end
redirect_to root_path, :notice => "You just send #{emails.size} invitations!"
else
redirect_to(:back)
end
end
end
class FreeRegistrationCoupon < ActiveRecord::Base
before_save :generate_token
attr_accessor :recipient_email, :sender_id
validates :recipient_email, :presence => true, :email => true
def generate_token
self.token = SecureRandom.hex
end
end
This is form which is in other controller CarsController#confirm:
<%= form_tag :controller => 'free_registration_coupons', :action => "send_invitations" do %>
<!-- errors -->
<%= label_tag :recipient_email_1 %>
<%= text_field_tag :recipient_email_1 %>
<%= label_tag :recipient_email_2 %>
<%= text_field_tag :recipient_email_2 %>
<%= label_tag :recipient_email_3 %>
<%= text_field_tag :recipient_email_3 %>
<%= submit_tag %>
<% end %>
I think you should have defined your form using:
<%= form_tag :controller => 'free_registration_coupons', :action => "send_invitations" do %>
<%= #error_message %>
<%= label_tag "recipient_email[1]" %>
<%= text_field_tag "recipient_email[1]" %>
<%= label_tag "recipient_email[2]" %>
<%= text_field_tag "recipient_email[2]" %>
<%= label_tag "recipient_email[3]" %>
<%= text_field_tag "recipient_email[3]" %>
<%= submit_tag %>
<% end %>
This way it will be easier to treat all email address on your controller and you can track those errors to display them afterwards:
class FreeRegistrationCouponsController < ApplicationController
def send_invitations
emails = params[:recipient_email]
emails.reject!{ |param, value| value.eql?("") }
errors = []
if emails.any?
emails.each do |param, value|
validation_result = FreeRegistrationCoupon.save(:recipient_email => value, :sender_id => current_user.id)
#MAILER
end
redirect_to root_path, :notice => "You just send #{emails.size} invitations!"
else
#error_message = "You have to include, at least, one e-mail address!"
render :name_of_the_action_that_called_send_invitations
end
end
end
I didnt test this code. Hope it helps!