rake db:seed not working as expected - ruby-on-rails-3

I am trying to seed a database with initial users. The first two are testing accounts and populate fine:
User.create! :name => "Name", :surname => "Lastname", :admin => 't', :email => "admin#testing.co", :encrypted_password => "Password"
User.create! :name => "name", :surname => "lastname", :admin => 'f', :email => "test#faker.tld", :encrypted_password => "Password"
However, the error NameError: undefined local variable or method 'name' for main:Object is triggered when I try to run:
8.times do
User.create! :name => Faker::Name.first_name, :surname => Faker::Name.last_name, :admin => 'f', :email => Faker::Internet.email(name + "." + surname), :encrypted_password => Faker::Internet.password(10)
end
I can't figure out the problem. Any help? Thanks.

Ended up with this:
8.times do
name = Faker::Name.first_name
surname = Faker::Name.last_name
encrypted_password = Faker::Internet.password(10)
user_list << [name, surname, 'f', Faker::Internet.email(name + "." + surname), encrypted_password]
end
user_list.each do |name, surname, admin, email, encrypted_password|
User.create!(name:name, surname:surname, admin:admin, email:email, encrypted_password:encrypted_password)
end

Related

Rails 3 execute custom sql query without a model

I need to write a standalone ruby script that is supposed to deal with database. I used code given below in rails 3
#connection = ActiveRecord::Base.establish_connection(
:adapter => "mysql2",
:host => "localhost",
:database => "siteconfig_development",
:username => "root",
:password => "root123"
)
results = #connection.execute("select * from users")
results.each do |row|
puts row[0]
end
but getting error:-
`<main>': undefined method `execute' for #<ActiveRecord::ConnectionAdapters::ConnectionPool:0x00000002867548> (NoMethodError)
what i am missing here?
SOLUTION
After getting solution from denis-bu i used it following way and that worked too.
#connection = ActiveRecord::Base.establish_connection(
:adapter => "mysql2",
:host => "localhost",
:database => "siteconfig_development",
:username => "root",
:password => "root123"
)
sql = "SELECT * from users"
#result = #connection.connection.execute(sql);
#result.each(:as => :hash) do |row|
puts row["email"]
end
Maybe try this:
ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)
connection = ActiveRecord::Base.connection
connection.execute("SQL query")
I'd recommend using ActiveRecord::Base.connection.exec_query instead of ActiveRecord::Base.connection.execute which returns a ActiveRecord::Result (available in rails 3.1+) which is a bit easier to work with.
Then you can access it in various the result in various ways like .rows, .each, or .to_hash
From the docs:
result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>
# Get the column names of the result:
result.columns
# => ["id", "title", "body"]
# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
[2, "title_2", "body_2"],
...
]
# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
{"id" => 2, "title" => "title_2", "body" => "body_2"},
...
]
# ActiveRecord::Result also includes Enumerable.
result.each do |row|
puts row['title'] + " " + row['body']
end
note: copied my answer from here
You could also use find_by_sql
# A simple SQL query spanning multiple tables
Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
> [#<Post:0x36bff9c #attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
How about this :
#client = TinyTds::Client.new(
:adapter => 'mysql2',
:host => 'host',
:database => 'siteconfig_development',
:username => 'username',
:password => 'password'
sql = "SELECT * FROM users"
result = #client.execute(sql)
results.each do |row|
puts row[0]
end
You need to have TinyTds gem installed, since you didn't specify it in your question I didn't use Active Record

Keep getting A sender (Return-Path, Sender or From) required to send a message

class SupportMailer < ActionMailer::Base
default :from => "email1#gmail.com"
def welcome_email(ticket)
case ticket.game
when "gameone"
#ticket = ticket
headers["Reply-to"] = "email1+#{ticket.token}#gmail.com"
headers["Return-Path"] = "email1+#{ticket.token}#gmail.com"
mail(:from => "email1#gmail.com", :to => ticket.email, :subject => "Welcome to 1 Support Ticket")
when "gametwo"
#ticket = ticket
headers["Reply-to"] = "email2+#{ticket.token}#gmail.com"
headers["Return-Path"] = "email2+#{ticket.token}#gmail.com"
mail(:from => "email2#gmail.com", :to => ticket.email, :subject => "Welcome to 2 Support Ticket")
when "gamethree"
#ticket = ticket
headers["Reply-to"] = "email3+#{ticket.token}#gmail.com"
header["Return-Path"] = "email3+#{ticket.token}#gmail.com"
mail(:from => "email3#gmail.com", :to => ticket.email, :subject => "Welcome to 3 Support Ticket")
end
end
end
I've set my default :from, so I don't get why I keep getting this message, I'm also trying to set it via headers to no avail.
here are my settings
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:user_name => "emailx#gmail.com",
:password => "password",
:authentication => "plain",
:enable_starttls_auto => true
}
I just call it like so, SupportMailer.support_response(#message).deliver
How do I fix this?
I notice you have no default case for the case statement. If you never end up calling the "mail" method inside your methods in the Mailer class, you'll get that error. Try moving your case statement out to where you call SupportMailer, maybe have methods for each case. That way you never call the SupportMailer unless you've already determined the correct ticket game.

simple_form custom input for a composed_of aggregate attribute in Rails

I'm trying to write a custom input for the simple_form gem for a Rails 3 model which has a composed_of aggregate attribute. See the example below.
I tried using fields_for but it generates params like "person"=>{"name"=>{"fname"=>"James","middle"=>"T","lname"=>"Kirk"} which does not get handled by Person.create nor update_attributes like an association would.
Gives the following error
undefined method `fname' for {"fname"=>"James", "middle"=>"T", "lname"=>"Kirk"}:ActiveSupport::HashWithIndifferentAccess
How would you implement this?
Example
$ rails g scaffold person last_name:string first_name:string middle_name:string
lib/fullname.rb
class Fullname
attr_reader :fname, :middle, :lname
def initialize(fname, middle, lname)
#fname, #middle, #lname = fname, middle, lname
end
end
app/models/person.rb
class Person < ActiveRecord::Base
composed_of :name,
:class_name => 'Fullname',
:mapping =>
[ # database # Fullname
[:first_name, :fname],
[:middle_name, :middle],
[:last_name, :lname]
],
:allow_nil => true
end
app/views/people/_form.html.haml
= simple_form_for #person do |f|
= f.input :name, :as => :fullname
= f.submit 'Save'
app/inputs/fullname_input.rb
class FullnameInput < SimpleForm::Inputs::Base
def input
#builder.simple_fields_for attribute_name, :validate => false do |form|
[ 'First:', form.input_field(:fname, :size => 10),
'Middle:', form.input_field(:middle, :size => 5),
'Last:', form.input_field(:lname, :size => 10)
].join(' ').html_safe
end
end
end

Devise:: Cannot create user through rake db:seed (failure confirmation_instructions)

User model has a function
def self.createadmin(
User.create(:email => "abc#gmail.com", :password => "123456e", :password_confirmation => "123456e", :terms_of_service => '1')
end
In rake db:seed, I have to call User.createadmin
However, this fails
ActionView::Template::Error: ActionView::Template::Error
from /Users/bever/Projects/tr/app/views/devise/mailer/confirmation_instructions.html.erb:3:in `_app_views_devise_mailer_confirmation_instructions_html_erb___1974818942364630283_2154906860'
Then I changed the code in createadmin
begin
User.create(:email => "abc#gmail.com", :password => "123456e", :password_confirmation => "123456e", :terms_of_service => '1')
rescue => e
User.create(:email => "abc#gmail.com", :password => "123456e", :password_confirmation => "123456e", :terms_of_service => '1')
end
It works! Any clue why this is happening?
Have you tried seeding from the db/seeds.rb file instead of the model? When you try to do it on the model, devise is probably trying to send the conformation mail.
You should create your admin user on the seeds.rb file like this
User.create(:email => "abc#gmail.com", :password => "123456e", :password_confirmation => "123456e", :terms_of_service => '1')
Remember that if you are using confirmable module of devise you should add this field to the query.
:confirmed_at => Time.now
Maybe you should add the confirmation tokens and other fields useful to administrate your admin account via your rails app and not on the console.
PD: Probably if you post more of the error shown and maybe the line in the view I can help you more.
Greetings

Can't create Custom inputs for some (Text, Booleans, ...) types, with SimpleForm

I can't figure out why this is not working as it should - or - I'm missing something important ?
Here's the list of the mapped types from simple_form / lib / simple_form / form_builder.rb:
map_type :text, :to => SimpleForm::Inputs::TextInput
map_type :file, :to => SimpleForm::Inputs::FileInput
map_type :string, :email, :search, :tel, :url, :to => SimpleForm::Inputs::StringInput
map_type :password, :to => SimpleForm::Inputs::PasswordInput
map_type :integer, :decimal, :float, :to => SimpleForm::Inputs::NumericInput
map_type :range, :to => SimpleForm::Inputs::RangeInput
map_type :select, :radio, :check_boxes, :to => SimpleForm::Inputs::CollectionInput
map_type :date, :time, :datetime, :to => SimpleForm::Inputs::DateTimeInput
map_type :country, :time_zone, :to => SimpleForm::Inputs::PriorityInput
map_type :boolean, :to => SimpleForm::Inputs::BooleanInput
First problem, I can extend StringInput class as:
#app/inputs/string_input.rb
class StringInput < SimpleForm::Inputs::StringInput
def input
if #builder.show?
content_tag(:p, #builder.object[attribute_name], :class => :show)
else
super
end
end
end
(I've extended the builder with a show? method to detect the context: action == 'show')
This is working most of the time but not when :as => :string is present :
<%= f.input :estimated_duration_rendered,
:as => :string,
:label => mt(:estimated_duration),
:hint => mt(:estimated_duration_hint),
:error => false,
:required => false,
:input_html => { :class => :digits_11, :placeholder => mt(:estimated_duration_placeholder), :value => format_duration(resource.estimated_duration, true) }
%>
Second problem, I can create custom inputs for StringInput, DateTimeInput, CollectionInput and BooleanInput but all the others are not working. For example:
#app/inputs/text_input.rb
class TextInput < SimpleForm::Inputs::TextInput
def input
if #builder.show?
"I will never show..."
else
super
end
end
end
Even if I have this helper in my form:
<%= f.input :description,
:label => mt(:description),
:hint => mt(:description_hint, :max => MyModel::DESC_MAX_LENGTH),
:input_html => { :class => :large, :rows => 8, :cols => 1, :maxlength => MyModel::DESC_MAX_LENGTH, :placeholder => mt(:description_placeholder) },
:error => false
%>
Of course, description has a text data type.
What Am I doing wrong ?
Thank you.
Fro
Well, to use this functionality you just need the 1.5.1 version of SimpleForm. :-)