Trying to transfer to a recipient through stripe - ruby-on-rails

I'm trying to pass an order and transfer the money to a recipient which created the listing.
Every time i try to pass an order i get a error "Cannot transfer to a recipient that has no default payment account". When a user makes a new listing they must provide information like Country, Routing Number and Account Number only ones. I will show my code and if anybody can see an error i did it would help a lot.
When i try this in the console this is what i get
rp = Stripe::Recipient.retrieve(user.recipient)
=> #<Stripe::Recipient:0x8333f120 id=rp_14X1Sz4SnElBeDRiOQWxitGL> JSON: {
"id": "rp_14X1Sz4SnElBeDRiOQWxitGL",
"object": "recipient",
"created": 1409365189,
"livemode": false,
"type": "individual",
"description": null,
"email": "perez#mezarina.me",
"name": "Andy Perez",
"verified": false,
"metadata": {},
"active_account": null,
"cards": {"object":"list","total_count":0,"has_more":false,"url":"/v1/recipients/rp_14X1Sz4SnElBeDRiOQWxitGL/cards","data":[]},
"default_card": null
}
This is my Listings controller
class ListingsController < ApplicationController
def index
if params[:query].present?
#listings = Listing.search(params[:query], page: params[:page])
else
#listings = Listing.all.order("created_at desc").limit(12)
end
end
def show
#listing = Listing.find(params[:id])
end
def new
#listing = Listing.new
end
def create
#listing = Listing.new(listing_params)
#listing.user_id = current_user.id
if current_user.recipient.blank?
Stripe.api_key = ENV["STRIPE_API_KEY"]
token = params[:stripeToken]
recipient = Stripe::Recipient.create(
:name => #listing.user.name,
:email => #listing.user.email,
:type => "individual",
:bank_account => token
)
current_user.recipient = recipient.id
current_user.save
end
if #listing.save
redirect_to #listing
else
render :new
end
end
def seller
#listing = Listing.where(user: current_user)
end
def favorite
if #listing = Listing.find(params[:id])
current_user.mark_as_favorite #listing
redirect_to #listing
end
end
def unfavorite
#listing = Listing.find(params[:id])
#listing.unmark :favorite, :by => current_user
redirect_to #listing = :back
end
private
def listing_params
listing_params = params.require(:listing).permit(:name, :description, :price, :image, :anime_id).merge(:user_id => current_user.id)
end
end
This is my orders controller
class OrdersController < ApplicationController
def sales
#orders = Order.all.where(seller: current_user)
end
def purchases
#orders = Order.all.where(buyer: current_user)
end
def new
#order = Order.new
#listing = Listing.find(params[:listing_id])
end
def create
#order = Order.new(order_params)
#listing = Listing.find(params[:listing_id])
#seller = #listing.user
#order.listing_id = #listing.id
#order.buyer_id = current_user.id
#order.seller_id = #seller.id
recipient_id = #listing.user.recipient
Stripe.api_key = ENV["STRIPE_API_KEY"]
token = params[:stripeToken]
begin
charge = Stripe::Charge.create(
:amount => (#listing.price * 100).floor,
:currency => "usd",
:card => token
)
flash[:notice] = "Thanks for ordering!"
rescue Stripe::CardError => e
flash[:danger] = e.message
end
transfer = Stripe::Transfer.create(
:amount => (#listing.price * 95).floor,
:currency => "usd",
:bank_account => token,
:recipient => #seller.recipient
)
if #order.save
redirect_to root_path
else
render :new
end
end
private
def set_order
#order = Order.find(params[:id])
end
def order_params
order_params = params.require(:order).permit(:address, :city, :state, :buyer_id, :seller_id)
end
end
New listing form
<section class="new-listing">
<div class="row">
<div class="medium-3 medium-centered columns end">
<%= simple_form_for #listing do |f| %>
<%= f.file_field :image %>
<%= f.input :name, placeholder: 'Name',label: false %>
<%= f.input :price, placeholder: 'Price in USD',label: false %>
<%= f.association :anime, prompt: 'Pick anime',label: false %>
</div>
<div class="medium-12 columns description">
<%= f.input :description, :input_html => { :cols => 50, :rows => 10 }, label: false, placeholder: 'Write the product description here......' %>
<% if current_user.recipient.blank? %>
<br>
<h1>Bank Account Information</h1>
<div class="form-group">
<%= label_tag :country %>
<%= text_field_tag :country, nil, { :name => nil, :'data-stripe' => "country" } %>
</div>
<div class="form-group">
<%= label_tag :routing_number %>
<%= text_field_tag :routing_number, nil, { :name => nil, :'data-stripe' => "routingNumber"} %>
</div>
<div class="form-group">
<%= label_tag :account_number %>
<%= text_field_tag :account_number, nil, { :name => nil, :'data-stripe' => "accountNumber"} %>
</div>
<% end %>
<div class="medium-1 medium-centered columns end">
<%= f.submit 'Done', class: 'button tiny' %>
</div>
<% end %>
</div>

The console code you're showing also reflects that there's no account setup for the recipient (to which we'd transfer funds). Hence, the error message. I don't see anywhere in your code where you're creating the destination account (e.g., bank or debit card).
Also, just to be clear, if you process a charge today, those funds won't be available for transfer until X days later (X = depends upon your account).
Hope that helps,
Larry
PS I work on Support at Stripe.

Related

Stripe checkout on wizard page via wicked gem gives error on loading, how to resolve?

Right now I get this error message when the submit.html.erb loads: Cannot charge a customer that has no active card.
I want to understand how I can improve my controller. The goal is to not have the error message when the submit page loads. But only if there's an actual user submitting false information.
class SubmissionsController < ApplicationController
include Wicked::Wizard
steps :name, :details, :comments, :submit, :thankyou
def show
#company = Company.find(params[:company_id])
render_wizard
end
def update
#company = Company.find(params[:company_id])
# one time checkout
#amount = 50
#description = 'Premium Package'
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken]
)
Stripe::Charge.create(
:customer => customer.id,
:amount => #amount,
:description => #description,
:currency => 'eur'
)
rescue Stripe::CardError => e
flash[:error] = e.message
params[:company][:status] = step.to_s
params[:company][:status] = 'active' if step == steps.last
#company.update_attributes(company_params)
render_wizard #company
end
private ...
Here's the submit.html.erb
<%= form_for #company, url: wizard_path, method: :put do |f| %>
<article>
<% if flash[:error].present? %>
<div id="error_explanation">
<p><%= flash[:error] %></p>
</div>
<% end %>
<label class="amount">
<span>Amount: €0.50</span>
</label>
</article>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
data-description=<% #description %>
data-amount=<% #amount %>
data-locale="auto"></script>
<% end %>
If I can provide more context, please advise.
Refactored into this, now it works:
class SubmissionsController < ApplicationController
include Wicked::Wizard
steps :name, :details, :comments, :submit, :thankyou
def show
get_company
set_package
render_wizard
end
def update
case step
when :thankyou
get_company
render_wizard #company
when :submit
get_company
set_package
if request.put?
create_customer
do_payment
render_wizard #company
end
else
get_company
params[:company][:status] = 'active' if step == steps.last
#company.update_attributes(company_params)
render_wizard #company
end
end
def get_company
#company = Company.find(params[:company_id])
end
def create_customer
#customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken]
)
end
def set_package
#amount = 50
#amount_in_decimals = #amount / 100.00
#description = "Premium Package"
end
def do_payment
Stripe::Charge.create(
:customer => #customer.id,
:amount => #amount,
:description => #description,
:currency => "eur"
)
rescue Stripe::CardError => e
flash[:error] = e.message
end
and for the view
<label class="amount">
<span>Amount: <%= number_to_currency(#amount_in_decimals, :precision => 2, :locale => :nl) %></span>
</label>
</article>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
data-name="RailsApp!"
data-description='<%= #description %>'
data-amount=<%= #amount %>
data-locale="auto"
data-currency="eur"></script>
<% end %>

Model Validation Messages Rails 4 form errors not showing up

I have a form which allows a user to invite multiple people via adding emails in a comma separated list. In my "Participant" model, I have a call to validate the uniqueness of the email entered (scoped by "project_id"). In the model validation, it gives a place to explain the error (message), but I can't get that error to show up on my form if the validation fails.
If a user enters the email of a person that has already been added, how can I get the errors message to render?
participant.rb
class Participant < ActiveRecord::Base
validates :email, uniqueness: {case_sensitive: false, scope: :project_id, message: "Looks like you\'ve already added this person."}
end
participant_controller.rb
def new_participant
#new_participants = Participant.new
#participants = Participant.where(project_id: #project.id).includes(:user)
#template = Template.find(#project.template_id)
#address = Address.where(project_id: #project.id).first
#food = ProjectRestriction.where(project_id: #project.id)
end
def add_participant
#added_by = User.find(current_user.id)
#new_participants = params[:new_participants][:email].split(/,\s*/)
#new_participants.each do |t|
newpart = Participant.new(:email => t, :project_id => #project.id, :level => 4,
:participant_cat_id => 2, :last_updated_by => current_user.id, :added_by => current_user.id, :status => 'unseen')
respond_to do |format|
if newpart.save
ProjectMailer.notify_recipient(newpart, #project, #added_by, #participant_invite ).deliver_later
self.response_body = nil
redirect_to participants_path(p: #project.id, w: 'recipient')
else
format.html { redirect_to new_participant_path(p: #project.id)}
format.json { render json: #new_participants.errors, status: :unprocessable_entity }
end
end
end
end
form
<%= form_for :new_participants, url: add_participant_path( :p => #project.id), html: { :multipart => true, :class=> "form-horizontal", id: "basicForm" } do |f| %>
<% if #new_participants.errors.any? %>
<h2>OOPS!</h2>
<ul>
<% #new_participants.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul></div>
<% end %>
<div class="form-group ">
<label class="form-label dk-aqua"> Email: <span class="asterisk">*</span></label>
<%= f.text_field :email, :autofocus => true, :required => true, :maxlength => 55, :placeholder => 'Email(s)', :class => 'form-control' %>
</div>
<%= f.submit 'INVITE', :class => 'btn btn-aqua btn-lg btn-block',
:style => 'margin-bottom:-5px' %>
<% end %>
Your main issues are:
you are creating a respond block for each email in the request. 1 request = 1 response.
The objects in stored in memory in #new_participants are not actually saved.
In your views your are treating #new_participants as if it where a single resource.
Pay attention to pluralization when naming routes, variables and actions.
def add_participants
#added_by = User.find(current_user.id)
#new_participants = params[:new_participants][:email].split(/,\s*/)
#new_participants.map do |email|
newpart = Participant.new(
:email => email,
:project_id => #project.id,
:level => 4,
:participant_cat_id => 2,
:last_updated_by => current_user.id,
:added_by => current_user.id,
:status => 'unseen'
)
if newpart.save
ProjectMailer.notify_recipient(newpart, #project, #added_by, #participant_invite ).deliver_later
end
new_part
end
#invalid = #new_participants.reject(&:valid?)
if #invalid.any?
respond_to do |format|
format.html { redirect_to new_participant_path(p: #project.id)}
format.json { render json: #new_participants.map(&:errors), status: :unprocessable_entity }
end
else
respond_to do |format|
redirect_to participants_path(p: #project.id, w: 'recipient')
end
end
end
<ul>
<% #new_participants.each |p| %>
<% p.errors.messages.each do |msg| %>
<li><%= msg %></li>
<% end if p.errors.any? %>
<% end %>
</ul>

How to Cancel Paypal Subscription?

I finally figured out how to implement PayPal Recurring Billing using this tutorial. http://railscasts.com/episodes/289-paypal-recurring-billing
Everything works, But how does one cancel the subscription....
Below is all of the code I've written, and I've also added some comments/questions
ERROR
app/controllers/subscriptions_controller.rb:27:in `show'
Couldn't find Subscription with id=cancel_account
Please help new to rails. :)
CONTROLLER
class SubscriptionsController < ApplicationController
def new
plan = Plan.find(params[:plan_id])
#subscription = plan.subscriptions.build
#subscription.user_id = current_user.id
if params[:PayerID]
#subscription.paypal_customer_token = params[:PayerID]
#subscription.paypal_payment_token = params[:token]
#subscription.email = #subscription.paypal.checkout_details.email
end
end
def create
#subscription = Subscription.new(params[:subscription])
if #subscription.save_with_payment
redirect_to #subscription, :notice => "Thank you for subscribing!"
else
render :new
end
end
def destroy
#subscription = current_user.subscription
#previous_plan = #subscription.plan
if #subscription.cancel_recurring
flash[:success] = 'Subscription Canceled.'
end
redirect_to some_path
end
def paypal_checkout
plan = Plan.find(params[:plan_id])
subscription = plan.subscriptions.build
redirect_to subscription.paypal.checkout_url(
return_url: new_subscription_url(:plan_id => plan.id),
cancel_url: root_url
)
end
end
MODELS
class Subscription < ActiveRecord::Base
attr_accessible :paypal_customer_token, :paypal_recurring_profile_token,
:plan_id, :user_id, :email, :paypal_payment_token
attr_accessor :paypal_payment_token
belongs_to :plan
belongs_to :user
validates_presence_of :plan_id
validates_presence_of :email
validates_presence_of :user_id
def save_with_payment
if valid?
if paypal_payment_token.present?
save_with_paypal_payment
end
end
def paypal
PaypalPayment.new(self)
end
def save_with_paypal_payment
response = paypal.make_recurring
self.paypal_recurring_profile_token = response.profile_id
save!
end
def payment_provided?
paypal_payment_token.present?
end
end
class PaypalPayment
def initialize(subscription)
#subscription = subscription
end
def checkout_details
process :checkout_details
end
def checkout_url(options)
process(:checkout, options).checkout_url
end
def make_recurring
process :request_payment
process :create_recurring_profile, period: :monthly, frequency: 1,
start_at: Time.zone.now + 1.month
end
def cancel_recurring
response = ppr.cancel_subscription(at_date_end: true) #Needs a end period field in
self.current_date_end_at = Time.at(response.current_date_end)
self.plan_id = plan.id
self.status = "canceled"
return self.save
end
private
def process(action, options = {})
options = options.reverse_merge(
token: #subscription.paypal_payment_token,
payer_id: #subscription.paypal_customer_token,
description: #subscription.plan.name,
amount: #subscription.plan.price.to_i,
currency: "USD"
)
response = PayPal::Recurring.new(options).send(action)
raise response.errors.inspect if response.errors.present?
response
end
end
VIEWS
<%= form_for #subscription do |f| %>
<%= f.hidden_field :plan_id %>
<%= f.hidden_field :user_id %>
<%= f.hidden_field :paypal_customer_token %>
<%= f.hidden_field :paypal_payment_token %>
<% unless #subscription.payment_provided? %>
<div class="field">
<%= radio_button_tag :pay_with, :paypal %>
<%= label_tag :pay_with_paypal do %>
<%= image_tag "paypal.png" %>
<% end %>
</div>
<% end %>
*** WHAT WOULD BE THE LINK TO CANCEL THE SUBSCRIPTION ***
<%= link_to image_tag("https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif"),
paypal_checkout_path(plan_id: #subscription.plan_id) %>
<%= link_to "Cancel Subscription", cancel_account_subscriptions_path(plan_id:
#subscription.plan_id) %>
<div id="billing_fields">
<div class="field">
<%= f.label :email %>
<%= f.text_field :email %>
</div>
<% if #subscription.payment_provided? %>
Payment has been provided. Click "Subscribe" to complete the subscription.
<% end %>
<div class="actions">
<%= f.submit "Subscribe" %>
</div>
</div>
<% end %>
ROUTES
App::Application.routes.draw do
resources :subscriptions do
collection do
delete :cancel_account
end
end
get 'paypal/checkout', to: 'subscriptions#paypal_checkout'
end
To destroy a users paypal subscription you should create a destroy action in your subscription model.
Subscription_controller.rb
def destroy
#subscription = current_user.subscription
#previous_plan = #subscription.plan
if #subscription.cancel_recurring
flash[:success] = 'Subscription Canceled.'
end
redirect_to some_path
end
In your model get the current user and cancel their subscription. If the user is subscribed monthly but canceled within 2days out of the 30 days, their account subscription should be valid until the at_end_date period(just a heads up).
def cancel_recurring
response = ppr.cancel_subscription(at_date_end: true) #Needs a end period field in
self.current_date_end_at = Time.at(response.current_date_end)
self.plan_id = plan.id
self.status = "canceled"
return self.save
end
Routes.rb
resources :subscriptions do
collection do
delete :cancel_account
end
end
In your view you would iterate through the plans like so
<% #plans.each do |plan| %>
<%= link_to "Cancel Account", cancel_account_subscriptions_path(#subscription, plan_id: plan.id), method: :delete %>
<% end %>

Create method not submitting POST request

I have a controller in a rails app whereby a user can create a holiday request, it seems that when I fill out the necessary information it is not doing the POST request and submitting my form. My output in the RailsPanel follows: Rails Panel. From this its as if it is doing the GET request when surely on it should do a GET then a POST. I believe I have messed up somewhere around my create method. Any feedback would be great thank you!
controller
class HolidaysController < ApplicationController
before_filter :authenticate_user!
before_filter :admin_user, :only => [:index, :update, :edit, :absence]
before_filter :correct_user, :only => [:delete]
def new
#holiday = Holiday.new
#user = current_user
end
def show
#holiday = Holiday.find(params[:id])
c_u = current_user
end
def create
#user = current_user
#holiday = current.holidays.build(params[:holiday])
#holiday.approver_id = approval_method(current_user, #holiday)
if #holiday.save
redirect_to root_path
flash[:success]= "holiday application sent!"
else
render :new
end
end
def myholidays
#holidays = current_user.holidays.all
end
def index
#holidays = Holiday.all
end
def absence
#show the holidays where the approver id matches the current user id
#and state = "requested"'
#user = current_user
if current_user.role? :administrator
# a admin can view all current holiday requests
#holidays = Holiday.all( :conditions => 'state = "requested"')
else
#otherwise an admin sees the holiday requests that they are approvers for
#holidays = Holiday.all(:conditions => ["approver_id = #{current_user.id}", "state = requested"])
end
end
def edit
today = Date.today
#holidays = Holiday.all
#month = (params[:month] || (Time.zone || Time).now.month).to_i
#year = (params[:year] || (Time.zone || Time).now.year).to_i
#shown_month = Date.civil(#year, #month)
#L51 - Parses the given representation of date and time with the given template
#and returns a hash of parsed elements.
#holiday = Holiday.find(params[:id])
end
def update
admin = User.find(current_user.role? :administrator)
holiday = Holiday.find(params[:id])
user = User.find(id = holiday.user_id)
if holiday.update_attributes(params[:holiday])
if holiday.state == "approved"
user.absentdays = user.absentdays - (holiday.days_used).to_i
user.save
end
redirect_to absence_path, :notice => "Request updated"
else
render 'edit'
end
end
def destroy
Holiday.find(params[:id]).destroy
redirect_to root_url, :notice => "Request deleted"
end
private
def current_user?(user)
user == current_user
end
def admin_user
redirect_to dashboard_path, :notice => "You must be an admin to do this!" unless current_user.role? :administrator
end
def signed_in_user
redirect_to login_path, notice: "Please sign in." unless signed_in?
end
def correct_user
#user = current_user
redirect_to dashboard, notice: "You are not the correct user." unless current_user?(#user) or current_user.role? :administrator
end
def approval_method(current_user, holiday_to_approve)
found = false
days = holiday_to_approve.days_used
user = current_user
approver = user.role? :administrator
until found == true
#Admins should be automatically approved and have no approvers
if approver == nil
holiday_to_approve.state = "approved"
#if user absent days is equal to absent days - day and convert to integer
user.absentdays = user.absentdays - (days).to_i
user.save
found = true
else
redirect_to dashboard_path, :notice => "Request complete"
end
break if found == true
end
end
end
holidays/show.html.erb
<form class="form">
<p>You have<b><%= #user.absentdays %> days of holiday left.</b></p>
<%= form_for #holiday do |f| %>
<% if #holiday.errors.any? %>
<div>
<h2>Form is invalid</h2>
<ul>
<% for message in #holiday.error.full_messages %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
Select the dates required for absence<br>
Start: <%= datepicker_input "holiday", "start_at", :minDate => 0, :dateFormat => "yy-mm-dd" %><br>
End: <%= datepicker_input "holiday", "end_at", :minDate => 0, :dateFormat => "yy-mm-dd" %>
<br><br>
Please select the type of absence you require<br>
<%= f.collection_select :type_id, Type.all, :id, :name, :prompt => "Select absence type" %>
<br><br>
<%= f.text_field :description %>
<br><br>
<%= f.submit "Submit Request", :class => "submit" %>
<% end %>
</form>
new.html.erb
<% provide(:title, 'apply for absence') %>
<p>You have <b><%= #user.absentdays %></b> days of holiday time left.</p>
<%= form_for #holiday do |f| %>
<% if #holiday.errors.any? %>
<div class="error_messages">
<h2>Form is invalid</h2>
<ul>
<% for message in #holiday.errors.full_messages %>
<li><%= message %></li>
<% end %>
</ul>
<% end %>
Select the dates required for absence<br>
start: <%= datepicker_input "holiday","start_at", :minDate => 0, :dateFormat => "yy-mm-dd" %><br>
end: <%= datepicker_input "holiday","end_at", :minDate => 0, :dateFormat => "yy-mm-dd" %>
<br><br>
Please select the type of absence you require<br>
<%= f.collection_select :type_id, Type.all, :id, :name, :prompt => "Select absence type" %>
<br><br>
Please provide a short description of the nature of your absence (if applicable)<br>
<%= f.text_field :description %>
<br><br>
<%= f.submit "submit" %>
<% end %>
</div>
The reason is, you are having a form in your holidays/show.html.erb but not in your holidays/new.html.erb.
According to rails convention, if form is submitted in new.html.erb, then by default the POST method is called of that particular controller.
But since your file is show.html.erb, you have to explicitly define your POST method in the form_for.
form_for #holiday , :url => { :action => :create }, :html => { :method => "post"} do |f|

Ruby on Rails: If error flags, page does not hold data entered by user

I have an app that allows users to enter a project into a database.
They get the option to either enter new data via a textbox for some field, or can select data via a drop down menu, that has been entered before for that field.
If the user fills out the form, then clicks submit, but there is a problem, like they have missed out one of the fields, the page flags up an error saying which fields are missing, which is fine.
However, if the user had entered new data in the text boxes, that gets deleted, and the first option in the drop down is selected instead.
Here is my project controller:
class ProjectsController < ApplicationController
before_filter :authenticate_user!
#:except => [:show, :index]
def index
#projects = Project.all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #projects }
end
end
# GET /projects/1
# GET /projects/1.json
def show
#project = Project.find(params[:id])
#project_project_id = params[:id]
respond_to do |format|
format.html # show.html.erb
format.json { render json: #project }
end
end
# GET /projects/new
# GET /projects/new.json
def new
#project = Project.new
#technol = Technol.new(params[:tech])
#all_technols = Technol.all
tech_ids = params[:technols][:id].reject(&:blank?) unless params[:technols].nil?
#project_technol = #project.projecttechnols.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: #project }
end
end
# GET /projects/1/edit
def edit
#project = Project.find(params[:id])
#project_technol = #project.projecttechnols.build
puts #project.inspect
puts #project.technols.inspect
end
# POST /projects
# POST /projects.json
def create
#project = Project.new(params[:project])
#project.client = params[:new_client] unless params[:new_client].blank?
#project.role = params[:new_role] unless params[:new_role].blank?
#project.industry = params[:new_industry] unless params[:new_industry].blank?
#project.business_div = params[:new_business_div] unless params[:new_business_div].blank?
if !params[:technols].nil?
params[:technols][:id].each do |tech|
if !tech.empty?
#project_technol = #project.projecttechnols.build(:technol_id => tech)
end
end
end
respond_to do |format|
if #project.save
format.html { redirect_to #project, notice: 'Project was successfully created.' }
format.json { render json: #project, status: :created, location: #project }
else
format.html { render action: "new" }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
# PUT /projects/1
# PUT /projects/1.json
# PUT /projects/1
# PUT /projects/1.json
def update
#project = Project.find(params[:id])
puts #project.inspect
puts #project.technols.inspect
#project.client = params[:new_client] unless params[:new_client].blank?
#project.role = params[:new_role] unless params[:new_role].blank?
#project.industry = params[:new_industry] unless params[:new_industry].blank?
#project.business_div = params[:new_business_div] unless params[:new_business_div].blank?
respond_to do |format|
if #project.update_attributes(params[:project])
format.html { redirect_to #project, notice: 'Project was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
# DELETE /projects/1
# DELETE /projects/1.json
def destroy
#project = Project.find(params[:id])
#project.destroy
respond_to do |format|
format.html { redirect_to projects_url }
format.json { head :no_content }
end
end
private
helper_method :sort_column, :sort_direction
def sort_column
Project.column_names.include?(params[:sort]) ? params[:sort] : "project_name"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
def per_page
params[:per_page] ||= 1
end
def page
params[:page] ||= 1
end
end
Here is some of my new project view
<%= stylesheet_link_tag "new" %>
<h1>Create New Project</h1>
<HTML>
<%= stylesheet_link_tag "form" %>
<%= form_for(#project) do |f| %>
<% if #project.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#project.errors.count, "error") %> prohibited this project from being saved:</h2>
<ul>
<% #project.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<CENTER>
<div id = "project_name">
<div class="project_name">
Project Name:
<%= f.text_field :project_name,:maxlength => 30 %>
</div>
</div>
<div id ="smallbox">
<div id = "status">
<div class="status">
<%= f.label :status %> :
<%#= f.select :status, [['Active'],['Completed']], {:include_blank => true} %>
<%= f.select :status, [['Active'],['Completed']] %>
</div></div>
<div class="client" STYLE="text-align: left;">
<%= label_tag :new_client, "Client" %><br/>
<%= text_field_tag :new_client, nil, :maxlength => 30 %>
Or
<%= f.select( :client, Project.all.map {|p| [p.client]}.uniq, :prompt => "Select previous..") %>
</div>
<div class="business_div" STYLE="text-align: left;">
<%= label_tag :new_business_div, "Business Division" %><br/>
<%= text_field_tag :new_business_div, nil, :maxlength => 30 %>
Or
<%= f.select( :business_div, Project.all.map {|p| [p.business_div]}.uniq, :prompt => "Select previous") %>
</div>
<div class="start_date" STYLE="text-align: left;">
<b>Start Date:</b>
<%= f.text_field :start_date, :class => 'datepicker', :style => 'width: 80px;' %>
</div>
</P>
<div class="create_button">
<div class="actions">
<%= f.submit "Save New Project", :class => "button", :confirm => "Are you sure you want to save the new project?" %>
</div>
</div>
</div> <%#= small div %>
<% end %>
<div class="back_button2">
<%= button_to "Back", projects_path , :class => "button", :method => "get" %>
</div>
Here is my project model
class Project < ActiveRecord::Base
attr_accessible :fullname, :edited_first_name, :edited_last_name, :first_name, :last_name, :business_div, :client, :customer_benefits, :edited_date, :end_date, :entry_date, :financials, :industry, :keywords, :lessons_learned, :project_name, :role, :start_date, :status, :summary, :technol_ids, :tech , :technols
validates_presence_of :business_div, :client, :customer_benefits, :end_date, :financials, :industry, :lessons_learned, :project_name, :role, :start_date, :status, :summary #, :keywords
validates_format_of :industry, :with => /\A[^\d]+\Z/, :message => "field should only have letters"
validates_format_of :business_div, :with => /\A[^\d]+\Z/, :message => "field should only have letters"
validates_format_of :client, :with => /\A[^\d]+\Z/, :message => "field should only have letters"
validates_format_of :exception_pm, :with => /\A[^\d]+\Z/, :message => "field should only have letters"
validates_format_of :project_owner, :with => /\A[^\d]+\Z/, :message => "field should only have letters"
validates_format_of :role, :with => /\A[^\d]+\Z/, :message => "field should only have letters"
has_many :projecttechnols
has_many :technols, :through => :projecttechnols
def set_fullname(a, b)
fullname = [a, b].join(' ')
end
accepts_nested_attributes_for(:technols)
end
If I need to include anything else please let me know. I have been stuck with this problem for some time now. Thank you in advance.
As railsdog suggests, use the data passed to Projects#create. Your form submits data and that data is held in a variable called params as key/value pairs. That variable should still be accessible from whichever view Projects#create renders.
What you need to do is to set some default content on your form elements. Here's an example for the text_field called "project_name"
<div class="project_name">
Project Name:
<%= f.text_field :project_name, params[:project_name],:maxlength => 30 %>
</div>
You should be able to do the same or something similar with any other fields.

Resources