Problems with 'seeding' data to different users - ruby-on-rails

I would like to seed some data to my wiki model user the 'faker gem'. I have created three users and would like to 'spread' 20 wikis over them.
I installed the faker gem, run bundle and set up my seedfile like this:
require 'faker'
# Create an admin user
admin = User.new(
email: 'admin2#example.com',
password: 'helloworld',
role: 'administrator'
)
admin.save!
# Create a moderator
moderator = User.new(
email: 'moderator2#example.com',
password: 'helloworld',
role: 'moderator'
)
moderator.save!
# Create a member
member = User.new(
email: 'member2#example.com',
password: 'helloworld'
)
member.save!
users = User.all
15.times do
Wiki.create!(
title: Faker::Lorem.sentence,
body: Faker::Lorem.paragraph
user: users.sample
)
end
wikis = Wiki.all
puts "Seeds finished"
If I run this I get an error:
SyntaxError: /Users/marcvanderpeet/Projects/bloc/blocipedia/db/seeds.rb:37: syntax error, unexpected tIDENTIFIER, expecting ')'
user: users.sample
I dont understand why I get this error as when Im running rails c I can just type in a user:
2.1.5 :001 > u = Wiki.new
=> #
Any clues on how to fix this?

You have a syntax error: the line
body: Faker::Lorem.paragraph
should end with a comma.

Already got it, forgot a ','. Devil is in the details!

Related

Don't stop rake task if raise an error

I have simple rake file.
It imports data from the .xls file to the database.
But some of the data is invalid. Then data is invalid rake stop excecuting script.
But I wan to just skip this row and try with the next.
Part of my code:
data.each do |row|
username = row[0].slice!(0..2) + row[1].slice!(0..2) + rand(100).to_s
username.downcase
password = "pass1234"
User.create!(
email: row[2].downcase,
username: username,
first_name: row[0],
last_name: row[1],
expiration_date: row[3],
password: password,
password_confirmation: password)
p 'done'
end
The error is about the validation, eg.:
rake aborted!
ActiveRecord::RecordInvalid: Validation failed: Expiration date must be after 2015-10-27
Script is stopped and valid records are not added.
Wrap it in a begin/rescue block.
data.each do |row|
begin
username = row[0].slice!(0..2) + row[1].slice!(0..2) + rand(100).to_s
username.downcase
password = "pass1234"
User.create!(
email: row[2].downcase,
username: username,
first_name: row[0],
last_name: row[1],
expiration_date: row[3],
password: password,
password_confirmation: password)
p 'done'
rescue => e
# log exception or ignore it.
end
end
Note that this works because the default rescue is for StandardError. Since ActiveRecord::RecordInvalid < StandardError. It will be 'catched'.
You could rescue the specific error first if you only want to do something with those specific errors.
(For reference also see the API: http://ruby-doc.org/core-2.2.0/Exception.html)

Bug when attempting to rake db:reset

I am attempting to setup an admin account for my first rails app.
This is the code I used to create the admin account:
admin = User.new(
name: 'Admin User',
email: 'admin#example.com',
password: 'helloworld',
password_confirmation: 'helloworld')
admin.skip_confirmation!
admin.save
admin.update_attribute(:role, 'admin')
Here is the code in question that is failing in Sublime:
50.times do
Post.create!(
user: users.sample,
topic: topics.sample.
title: Faker::Lorem.sentence
body: Faker::Lorem.paragraph
)
end
In terminal I am receiving this error message:
rake aborted!
SyntaxError: /Users/Alex/Desktop/code/Bloccit/db/seeds.rb:39: syntax error, unexpected ':', expecting ')'
title: Faker::Lorem.sentence
^
/Users/Alex/Desktop/code/Bloccit/db/seeds.rb:40: syntax error, unexpected ':', expecting keyword_end
body: Faker::Lorem.paragraph
^
/Users/Alex/Desktop/code/Bloccit/db/seeds.rb:41: syntax error, unexpected ')', expecting keyword_end
When I added the admin account, it appeared to add fine but after continuing on with my assignment I needed to log in with the admin account. After attempting it, it states the login information was incorrect. So I wanted to reset the DB to start over and this is where I am at now. Please help.
You missed comma separators after topic: topics.sample and title: Faker::Lorem.sentence.
50.times do
Post.create!(
user: users.sample,
topic: topics.sample, # <~~ Here
title: Faker::Lorem.sentence, # <~~ Here
body: Faker::Lorem.paragraph
)
end

In ActiveAdmin Gem, how to add invitation count to Admin model?

In my project I have implemented activeadmin gem, which is integrated with devise invitable. So in my application admin can invite a customer through an email. While inviting, i'm getting the following error:
*ActiveRecord::StatementInvalid in Admin::CustomersController#send_invitation
Mysql2::Error: Unknown column 'invitations_count' in 'field list': UPDATE `admin_users` SET `invitations_count` = COALESCE(`invitations_count`, 0) + 1 WHERE `admin_users`.`id` = 1*
This issue has happened after updating the gem devise_invitable to version 1.3.3
To fix it just create a migration
rails g migration AddInvitationsCountToAdminUsers invitations_count:integer
That should add invitations_count field to the table admin_users
For others who has got the same problem but in another table. Here is a migration for a general table users
rails g migration AddInvitationsCountToUsers invitations_count:integer
Such issue could be caught by rspec
it 'user can be invited with passing current_user' do
current_user_attr = {email: 'user1#example.com', password: 'xxxxxx', password_confirmation: 'xxxxxx', ... add your fields }
user_attr = {email: 'user2#example.com', password: 'xxxxxx', password_confirmation: 'xxxxxx', ... add your fields }
current_user = User.create!(current_user_attr)
user = User.create!(user_attr)
user.invite!(current_user).class.should eq(Mail::Message)
end

Nested attributes in rake task

I'm trying to create a rake task to populate my DB. I need to to create 1 user with a specifc set of deatails and 99 other randomly genraterated . The details that are required are for two Models at the same time, similar to a form with nested attribues. My model uses an after_create call back to create and link a users to a team. The team name by default is the users name
the current code that I have used it producing errors
sample_data.rake
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
user = User.create!(:profile_attributes => { name: Forgery::Name.full_name },
email: "test#example.com",
password: "123qwe",
password_confirmation: "123qwe")
99.times do |n|
:profile_attributes => { name: Forgery::Name.full_name },
email = Forgery::Internet.email_address
password = "password"
user = User.create!(email: email,
password: password,
password_confirmation: password)
end
end
end
Model that relys on the nested attibute.
class User < ActiveRecord::Base
after_create :set_user_on_team
private
def set_user_on_team
self.create_owned_team(:name => self.profile.name ).users << self
end
end
error message
rake aborted!
/lib/tasks/sample_date.rake:9: syntax error, unexpected tASSOC, expecting keyword_end
:profile_attributes => { name: Forgery::Name.full_name },
^
/lib/tasks/sample_date.rake:9: syntax error, unexpected ',', expecting keyword_end
I noticed some syntax errors in the 99.times block. You could try it like this:
99.times do |n|
profile_attributes = { name: Forgery::Name.full_name }
email = Forgery::Internet.email_address
password = "password"
user = User.create!(profile_attributes: profile_attributes, #my assumption
email: email,
password: password,
password_confirmation: password)
end

Testing Rails Controllers Inherited from Typus

I've been fighting with this for a couple of days and there doesn't seem to be much help online. I've looked at the Typus wiki, sample app, and tests and I appear to be doing things correctly but I stil get HTTP Status Code 302 (Redirect) where I expect 200 (Success) in my tests.
Below are what should be the appropriate files (with irrelevant stuff removed)
config/initializers/typus.rb (rails g typus:migration has been run as I have an admin_users table):
Typus.setup do |config|
# Application name.
config.admin_title = "Something"
# config.admin_sub_title = ""
# When mailer_sender is set, password recover is enabled. This email
# address will be used in Admin::Mailer.
config.mailer_sender = "noreply#somewhere.com"
# Define paperclip attachment styles.
# config.file_preview = :medium
# config.file_thumbnail = :thumb
# Authentication: +:none+, +:http_basic+
# Run `rails g typus:migration` if you need an advanced authentication system.
config.authentication = :session
# Define user_class_name.
config.user_class_name = "AdminUser"
# Define user_fk.
config.user_fk = "admin_user_id"
# Define master_role.
config.master_role = "admin"
end
config/typus/admin_user.yml
AdminUser:
fields:
default: first_name, last_name, role, email, locale
list: email, role, status
form: first_name, last_name, role, email, password, password_confirmation, locale
options:
selectors: role, locale
booleans:
status: Active, Inactive
filters: status, role
search: first_name, last_name, email
application: Admin
description: Users Administration
test/factories/admin_users.rb:
Factory.define :admin_user do |u|
u.first_name 'Admin'
u.last_name 'User'
u.email 'admin#somewhere.com'
u.role 'admin'
u.password 'password!'
u.token '1A2B3C4D5E6F'
u.status true
u.locale 'en'
end
test/functional/admin/credits_controller_test.rb:
require 'test_helper'
class Admin::CreditsControllerTest < ActionController::TestCase
setup do
#admin_user = Factory(:admin_user)
#request.session[:admin_user_id] = #admin_user.id
#request.env['HTTP_REFERER'] = '/admin/credits/new'
end
context "new" do
should "be successful" do
get :new
assert_response :success
end
end
end
#response.body:
<html>
<body>You are being redirected.
</body>
</html>
As you can see, I've set up the typus to use admin_user and admin_user_id for the session key. But for some reason that test fails getting 302 rather than 200. I'm sure this is because I'm doing something wrong that I just don't see. I've also created all these a gist, just in case someone prefers that.
Edited 2011-05-19 09:58am Central Time: Added Response body text per request.
I figured this out. It was a problem with the config/typus/admin_roles.yml file.
Before:
admin:
Category: create, read, update
Credit: read
...
After:
admin:
Category: create, read, update
Credit: read, create
...
The problem was that admin users didn't have access to the CREATE action on the admin/credits_controller which resulted in the user being sent back to the admin login address.
Giving admin users access to the action and changing the
#session[:admin_user_id]
to
#session[:typus_user_id] #Just like in the Typus docs
solved the problem. I had changed it to :admin_user_id because of the
config.user_fk = "admin_user_id"
in the typus config files, while trying to troubleshoot this issue.

Resources