I'm trying to add rows of a CSV to records in a table and everything seems to be working fine besides the fact that nothing actually shows up.
Here is my Rake task:
namespace :csv do
desc "Import CSV Data"
task :c_up => :environment do
require 'csv'
csv_file_path = 'db/main.csv'
CSV.foreach(csv_file_path, :headers => true) do |row|
row = Entry.create!({
:one => row[0],
:two => row[1],
:three => row[2],
:four => row[3],
:five =>row[4],
:six => row[5],
:seven => row[6],
:eight => row[7],
:nine => row[8],
:ten => row[9]
})
row.save
puts "Entry added!"
end
end
end
The headers in my CSV are named to match the attributes.
When I run the task I receive no errors and all of the "Entry added!" show up in the console. I've tried it without the row = and row.save as I've seen lots of examples without those but it doesn't help.
After the rake finishes there aren't any records at all. Is there something obvious I'm doing wrong? It seems like this is following most examples I've seen.
Edit Thanks for all your answers and comments! Obviously this is flawed all the way down to syntax, I'm going to try out your suggestions and I'll update this after. Thanks again!
Edit 2 It turned out to be a syntax issue that you guys all pointed out, so +1 for everyone thanks! The reason when I commented it still wasn't working was an unrelated problem which I wouldn't have figured out without #jvnill's comments.
try with:
row = Entry.new(
:one => row[0],
:two => row[1],
:three => row[2],
:four => row[3],
:five =>row[4],
:six => row[5],
:seven => row[6],
:eight => row[7],
:nine => row[8],
:ten => row[9]
)
row.save!
Without { } , and with save!
You could even try with this, to make it simpler:
Entry.create!(row.to_hash)
Entry.create! does not require being assigned to row nor does it require a row.save. Also know '{}' Just do:
Entry.create!(
:one => row[0],
:two => row[1],
:three => row[2],
:four => row[3],
:five =>row[4],
:six => row[5],
:seven => row[6],
:eight => row[7],
:nine => row[8],
:ten => row[9]
)
The create method will populate the row and save it as well.
namespace :csv do
desc "Import CSV Data"
task :c_up => :environment do
require 'csv'
csv_file_path = 'db/main.csv'
CSV.foreach(csv_file_path, :headers => true) do |row|
Entry.create!({
:one => row[0],
:two => row[1],
:three => row[2],
:four => row[3],
:five =>row[4],
:six => row[5],
:seven => row[6],
:eight => row[7],
:nine => row[8],
:ten => row[9]
})
end
end
end
Related
I have my site in ruby on rails and for subscription payments I am using the paypal paypal-sdk-rest gem. But I need the first payment to have a lower value and then the next payment to have the normal value so that users can subscribe and test the subscription. I have been reading in the paypal api and a trial with a lower value can be applied. Is it possible to apply trial to the paypal gem paypal-sdk-rest? this is my code of how I create the plans:
def creacion_planes
plan = Plan.new({
:name => 'Monthly $20',
:description => '$20 plan (monthly charge)',
:type => 'infinite',
:payment_definitions => [{
:name => 'Plan monthly $20',
:type => 'REGULAR',
:frequency_interval => '1',
:frequency => 'MONTH', #WEEK, DAY, YEAR, MONTH.
:cycles => '0',
:amount => {
:currency => 'USD',
:value => '20.00'
}
}],
:merchant_preferences => {
:return_url => complete_paypal_checkouts_planes_url,
:cancel_url => update_plan_url,
:max_fail_attempts => '0',
:auto_bill_amount => 'YES',
:initial_fail_amount_action => 'CONTINUE'
}
})
# Create plan
if plan.create
# Plan update activation object
plan_update = {
:op => 'replace',
:path => '/',
:value => {
:state => 'ACTIVE'
}
}
# Activate plan
if plan.update(plan_update)
puts("Billing plan activated with ID [#{plan.id}]")
redirect_to success_payment_path(:plan_id => plan.id, :plan => "plan_mensual20")
else
logger.error payment.error.inspect
end
else
logger.error payment.error.inspect
end
end
And this is my code of how I create the agreement:
def create
agreement = Agreement.new({
:name => params[:name],
:description => params[:description],
:start_date => (Time.now + 20*60).utc.iso8601, #'2020-04-26T23:00:04Z' (Time.now + 1.days).utc.iso8601
:plan => {
:id => params[:plan_id]
},
:payer => {
:payment_method => 'paypal'
}
})
if agreement.create
redirect = agreement.links.find{|v| v.rel == "approval_url" }.href
redirect_to redirect
else
logger.error agreement.error.inspect
end
end
Do not use that old paypal-ruby-sdk. It is obsolete and uses an old version of billing plans, which is not compatible with the current subscriptions API.
Instead, integrate the subscriptions API via direct HTTPS calls. Here is the guide: https://developer.paypal.com/docs/subscriptions/
An example with a trial period is provided.
I've tested my controller and have got strange errors like this:
expected: ("376")
got: (376)
Please stub a default value first if message might be received with other args as well.
This is my spec:
it 'should send confirm-email if information is good' do
sign_in user
allow(Order).to receive(:find).with(order.id.to_s).and_return(order)
allow(order).to receive(:finalize) {order}
allow(order.errors).to receive(:empty?) {true}
expect(OrderMailer).to receive_message_chain(:send_finish_notification, :deliver)
patch :save_order, {:id => order.id , :order => {:street_address => 'Baker street', :apt => '123#', :zip_id => zip.id, :frequency_id => frequency.id, :amount_per_hour => '5',
:extras_ids => '', :phone_number => '3213', :credit_card_number => '4242424242424242', :credit_card_cvv => '777',
:credit_card_expiration => '12/20', :source_information => ''}}
end
And I've got this error in some logically close specs. But some tests passes, like this one:
it 'should not update user data if order errors is not empty' do
sign_in user
allow(Order).to receive(:find).with(order.id.to_s).and_return(order)
allow(order).to receive(:finalize) {order}
allow(order.errors).to receive(:empty?) {false}
expect(User).to_not receive(:update_user_data)
patch :save_order, {:id => order.id, :order => {:street_address => 'Baker street', :apt => '123#', :zip_id => zip.id, :frequency_id => frequency.id, :amount_per_hour => '5',
:extras_ids => '', :phone_number => '3213', :credit_card_number => '4242424242424242', :credit_card_cvv => '777',
:credit_card_expiration => '12/20', :source_information => ''}}
end
to_s or to_i doesn't help. The error line in controller -
#order = Order.find(params[:id]
So what could be in that case ? 'Cause it looks like some specs passes, but similar to them don't. Any suggestions ?
The following code:
require 'csv'
desc "Import Voters from CSV File"
task :import => [:environment] do
file ="db/GOTV.csv"
CSV.foreach(file, :headers => true) do |row|
Voter.create({
:last_name => row[0],
:first_name => row[1],
:middle_name => row[2],
:name_suffix => row[3],
:primary_address => row[4],
:primary_city => row[5],
:primary_state => row[6],
:primary_zip => row[7],
:primary_zip4 => row[8],
:primary_unit => row[9],
:primary_unit_number => row[10],
:phone_number => row[11],
:phone_code => row[12],
:gender => row[13],
:party_code => row[14],
:voter_score => row[15],
:congressional_district => row[16],
:house_district => row[17],
:senate_district => row[18],
:county_name => row[19],
:voter_key => row[20],
:household_id => row[21],
:client_id => row[22],
:state_voter_id => row[23]
})
end
...is throwing the following error:
/Users/ecumbee/Desktop/cloudvoters/lib/tasks/import.rake:35: syntax error, unexpected $end, expecting kEND
end
^
I've tried removing the end, which throws the same error I've tried adding another end but it results in a can not compile error.
Edit:
error when adding a second end statement
Don't know how to build task 'db:import'
In the error message, $end refers to the end of the input file, while kEND refers to the end keyword, so it's complaining about a missing end, not an extra one.
If you still get a syntax error after adding another end, that's something unrelated to this error.
The end in your code is for the CSV.foreach ... do block. You're missing another end for the task ... to block.
If that still gives you a syntax error, edit your question and post that error instead.
I know you said you tried to add another end and it didn't help, but the problem with your file is that it's missing the end keyword that will end the task
task :import => [:environment] do
Then can you give more information about the error you're getting once you add the missing end ?
I'm trying to post to my controller in RSPEC, see anything wrong with this? It's failing w/o error:
it "should store create an IncomingMail record" do
lambda {
post 'create', {
"from" => 'XXX',
"to" => 'XXX',
"cc" => 'XXX',
"subject" => 'XXX',
"message_text" => 'XXX',
"message_html" => 'XXX' }
}.should change { IncomingMail.count }.by(1)
end
Updated:
it "should store create an IncomingMail record" do
post :create,
:from => 'xx',
:to => 'xx',
:cc => 'xx',
:subject => 'xx',
:message_text => 'xx',
:message_html => 'xx'
mail = IncomingMail.last(:order => 'created_at desc')
mail.from.should == 'xx'
end
Controller
class IncomingMailsController < ApplicationController
require 'iconv'
#make sure that rails doesn't raise an exception because we have no way of knowing the token
skip_before_filter :verify_authenticity_token
def create
begin
#incoming_mail = IncomingMail.create(
:from => params[:from],
:to => params[:to],
:cc => params[:cc],
:subject => params[:subject],
:message_text => message_text_utf8,
:message_html => message_html_utf8
)
.....
This is how i do it :
Route Example :
post 'train_ability/:ability' => :train_ability, :as => 'train_ability'
Spec :
it "should increase the strength ability by one point and also update the strength_points by one if strength is the trained ability" do
#user.str = 10
#user.str_points = 0
#user.save!
post :train_ability, :ability => 'str'
#user.reload
flash[:error].should be_nil
#user.str_points.should == 1
#user.str.should == 11
end
I'm stuck with a rake task that need to prepare a newsletter for Mailchimp.
Using rails 2.x stuff googled I now have this code:
desc "Sends newsletter to Mailchimp list"
task :send_newsletter => :environment do
begin
# get render helpers
av = ActionView::Base.new(Rails::Application::Configuration.new(Rails.root).view_path)
av.class_eval do
include ApplicationHelper
end
things = Stuff.do.things
h = Hominid::Base.new({:api_key => "xxx"})
h.create_campaign(
{
:list_id => "xxx",
:subject => "Hey...",
:from_email => "xxx",
:from_name => "xxx",
:to_email => "",
:auto_footer => true,
:generate_text => true
},
{
:html => av.render(:template => "stuff/newsletter", :locals => {:things => things}, :layout => false)
},
"regular")
rescue Exception => e
STDERR.puts ">>> #{e.to_yaml}"
end
And I get this error message: "undefined method `virtual_path' for false:FalseClass"
My first try was with render_to_string but I just can't access as it is in the controller not the view.
Any help would be greatly appreciated :)
:layout => nil ?