Rails test ActiveRecord error - ruby-on-rails-4

I initiated the test environment in my rails app, and when I test the user model with the default code, it throws the following error:
Test code:
test "the truth" do
assert true
end
1) Error:
UserTest#test_the_truth:
ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry '' for key 'index_users_on_email': INSERT INTO `users` (`created_at`, `updated_at`, `id`) VALUES ('2014-02-01 17:45:51', '2014-02-01 17:45:51', 298486374)
and inside my user model, I have the following associations
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :user_name , :email, :first_name ,:last_name , :presence => true
has_many :invitations
has_many :incoming_friends, -> { where(:status => '1') }, :class_name => "User", :foreign_key => "friend_id", :through => :invitations
has_many :outgoing_friends, -> { where(:status => '1') }, :class_name => "User", :foreign_key => "user_id", :through => :invitations

Firstly, check your user model fixture in test/fixtures/users.yml. If you have empty declarations of one and two:
one: {}
# column: value
#
two: {}
# column: value
it can cause a problems, because there is a lack of attributes. Remove this part or comment it:
#one: {}
# column: value
#
#two: {}
# column: value
And try run it again.

Related

Rails :has_many :through sort order issue in model

I am having some weird behavior in a Rails model and I'm not quite sure why. Thanks to anyone who can point me as to what I'm missing or not understanding.
The Problem
I have a model Car with a has_many :through relationship on Part through CarsPart. I expect accessing a car's parts to be in alphabetical order. I created the model specs and the controller specs. In the controller, the parts are ordered in alphabetical order as called out in the has_many relationship. In the controller spec, they are in order. In the model spec, they are not. I don't think it's tied to the testing framework because i've debugged the running server and see the same behavior.
The Code
Car
class Car < ActiveRecord::Base
has_many :cars_parts
has_many :parts, -> { order('name asc') }, through: :cars_parts, :dependent => :destroy
accepts_nested_attributes_for :cars_parts, :allow_destroy => true
validates :make, :model, presence: true
validate :validate_cars_parts
def validate_cars_parts
errors.add(:parts, "wrong number") if self.cars_parts.size < 1
self.cars_parts.each do |car_part|
part = Part.find(car_part.part_id)
errors.add(:parts, "doesn't exist") if part == nil
end
end
end
Part
class Part < ActiveRecord::Base
belongs_to :cars_part
has_many :cars, through: :cars_parts
validates :name, presence: true
end
CarsPart
class CarsPart < ActiveRecord::Base
belongs_to :car
belongs_to :part
end
Cars Controller Spec Passes
require 'rails_helper'
RSpec.describe CarsController, type: :controller do
render_views
context 'property features' do
describe "GET #show/id returns ordered parts" do
before :each do
#p4 = FactoryGirl.create(:part, :name => 'BPart2')
#p3 = FactoryGirl.create(:part, :name => 'APart2')
#p6 = FactoryGirl.create(:part, :name => 'BPart3')
#p5 = FactoryGirl.create(:part, :name => 'APart3')
#p2 = FactoryGirl.create(:part, :name => 'BPart1')
#p1 = FactoryGirl.create(:part, :name => 'APart1')
end
it 'returns parts in alphabetical order' do
car = FactoryGirl.create(:car, make: 'Nissan', model: 'Murano', parts: [#p4, #p3, #p6, #p5, #p2, #p1])
get :show, id: car.id, format: :json
expect(response).to have_http_status(:success)
expect(response).to render_template(:show)
response_json = JSON.parse(response.body)
response_json['parts'].each do |part|
puts part['id']
end
expect(response_json['parts'].size).to eq(6)
expect(response_json['parts'][0]['id']).to eq(#p1.id)
expect(response_json['parts'][1]['id']).to eq(#p3.id)
expect(response_json['parts'][2]['id']).to eq(#p5.id)
expect(response_json['parts'][3]['id']).to eq(#p2.id)
expect(response_json['parts'][4]['id']).to eq(#p4.id)
expect(response_json['parts'][5]['id']).to eq(#p6.id)
end
end
end
end
Car Model Spec Fails
require 'rails_helper'
RSpec.describe Car, type: :model do
context 'car parts' do
before :each do
#p4 = FactoryGirl.create(:part, :name => 'BPart2')
#p3 = FactoryGirl.create(:part, :name => 'APart2')
#p6 = FactoryGirl.create(:part, :name => 'BPart3')
#p5 = FactoryGirl.create(:part, :name => 'APart3')
#p2 = FactoryGirl.create(:part, :name => 'BPart1')
#p1 = FactoryGirl.create(:part, :name => 'APart1')
end
it 'returns parts in alphabetical order' do
car = FactoryGirl.create(:car, make: 'Nissan', model: 'Murano', parts: [#p4, #p3, #p6, #p5, #p2, #p1])
expect(car).to be_valid
expect(car.errors.messages.size).to eq(0)
expect(car.parts.size).to eq(6)
car.parts.each do |part|
puts part.id
end
expect(car.parts[0]['name']).to eq('APart1')
expect(car.parts[1]['name']).to eq('APart2')
expect(car.parts[2]['name']).to eq('APart3')
expect(car.parts[3]['name']).to eq('BPart1')
expect(car.parts[4]['name']).to eq('BPart2')
expect(car.parts[5]['name']).to eq('BPart3')
end
end
end
Summary
Please help me understand why when accessing them through the model they are not ordered, but when the controller looks them up and renders them, they are.
Thank you.
EDIT
The only way I have managed to get this to work is to create a 'ordered_parts' method that does the ordering and remove the order from the has_many. I had to change all my controllers to call 'ordered_parts' instead of the 'parts' method. Surely there is a better way. If anyone knows, please help.
def ordered_parts
self.parts.order('name asc')
end

Rails 4.1 7 Mongoid Activerecord is autosaving without calling .save

Let me explain first my model structure:
i have a status model:
class Status
include Mongoid::Document
include Mongoid::Search
include Mongoid::Timestamps
field :status_code, type: Integer
field :status_description, type: String
validates :status_code, :status_description, :transactiontype, :presence => true
belongs_to :transactiontype, :class_name => 'Transactiontype'
has_many :transactions, :class_name => 'Transaction', autosave: false
search_in :status_code, :status_description, :transactiontype => :transaction
def self.getStatus(transactiontype)
statuses = Status.where(:transactiontype_id => transactiontype).all
stats = []
puts "DATE DASHBOARD: #{Time.now.beginning_of_day} to #{Time.now.end_of_day}"
statuses.each do |status|
transactions = status.transactions.dateRange(Date.today.beginning_of_day, Date.today.end_of_day)
if transactions.length > 0
status.transactions = transactions
stats.push(status)
end
end
puts "SIZE : #{stats.size}"
stats
end
etc..
end
then i have another model called transactions:
class Transaction
include Mongoid::Document
include Mongoid::Search
include Mongoid::Timestamps
field :ref_no, type: String
field :trans_date, type: DateTime
belongs_to :status, :class_name => 'Status'
belongs_to :transactiontype, :class_name => 'Transactiontype'
validates :ref_no, :trans_date, :status, :presence => true
def self.dateRange(startdate,enddate)
puts "DATE : #{startdate} to #{enddate}"
if !startdate.blank?
where(:created_at => {"$gt" => startdate.beginning_of_day, "$lt" => enddate.end_of_day})
# where(:trans_date.gte => startdate.beginning_of_day, :trans_date.lte => enddate.end_of_day)
end
end
etc..
end
the weird part is that:
when im trying to execute:
Status.getStatus(params[:transactiontype_id])
i received the correct output but the transactions associated with the Status is being updated and each records before the filtered date is being updated with null status_id.
i already tried to add autosave: false but nothing works
can someone help me with this?
the solution is to convert the active record to json first
def self.getStatus(transactiontype)
statuses = Status.where(:transactiontype_id => transactiontype).all
stats = []
puts "DATE DASHBOARD: #{Time.now.beginning_of_day} to #{Time.now.end_of_day}"
statuses.each do |status|
ar_status = status.as_json
ar_status['transactions'] = status.transactions.dateRange(Date.today.beginning_of_day, Date.today.end_of_day)
if ar_status['transactions'].length > 0
stats.push(ar_status)
end
end
puts "SIZE : #{stats.size}"
stats
end
for some reason.. its auto saving the records.

Rails 4 Devise + Omniauth Github Routing Error

I'm using Rails 4.1.1 and I'm trying to create omniauth github with my devise gem in my application. But I get routing error, I'm following Railscast #235 revised on this topic.
Right now, I'm trying to do the same thing Ryan Bates is doing, which is raise omniauth.auth as a yaml to the screen, but I get the error:
No route matches [GET] "/auth/github/callback"
How do I fix this error?
Here you have my routes:
Rails.application.routes.draw do
devise_for :users, controllers: {omniauth_callbacks: "omniauth_callbacks"}
root to: 'questions#index'
resources :questions do
resources :answers, only: [:create]
end
resources :users, only: [:show]
#USERS CONTROLLER MY ROUTES
get "adding_likes/(:id)/(:like)/(:current_user_id)", to: "answers#adding_likes", as: :adding_likes
get "add_accept/(:answer_id)", to: "answers#accept", as: :accept
get "leaderboard", to: "users#leaderboard", as: :leaderboard
end
My controller:
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def all
raise request.env["omniauth.auth"].to_yaml
end
alias_method :github, :all
end
My user model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :omniauthable
# :recoverable, :rememberable and :trackable
devise :database_authenticatable, :registerable, :validatable, :omniauthable
has_attached_file :avatar, :styles => { :small => "100x100>" }
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
# has_attached_file :superstarbadge, :styles => { :small => "100x100>" }
# validates_attachment_content_type :superstarbadge, :content_type => /\Aimage\/.*\Z/
has_many :questions
has_many :answers
def to_s
email
end
end
Important part of my devise.rb
config.omniauth :github,NOT-VISIBILE,IN-HERE
Basically, you haven't added the routes for it. I think you've missed Ryan add it to his routes file. Just add this:
get "/auth/github/callback" => "yourController#yourAction"
but since you're using omniauth, it's better this way
get "/auth/:provider/callback" => "yourController#yourAction
And add the necessary views for it.

Rails 4 routes with single table inheritance and self references

I've been jumping between design patterns, firstly trying polymorphic, now landing on STI. The main goal is to implement a Server > Host > Guest model where a Server has Hosts, Hosts have Guests and each able to have Posts. Although not the main purpose of the question any ideas in the design matter would be helpful as this is my first rails or ruby project.
What I have now is:
class Device
has_may :children, :class_name => "Device", :foreign_key => "parent_id"
belongs_to :parent, :class_name => "Device"
has_many :posts
end
class Server,Host,Guest < Device
end
STI is used because Server,Host,Guest basically have the same attributes.
I'm having trouble setting up the routes and controllers so I could view a Server's children which would be of type Host or to create a new Server's Host.
First, a good thing would be to add the following things, making everything easier to use for you :
class Device < ActiveRecord::Base
has_many :children, :class_name => "Device", :foreign_key => "parent_id"
has_many :servers, -> { where type: "Server" }, :class_name => "Device", :foreign_key => "parent_id"
has_many :hosts, -> { where type: "Host" }, :class_name => "Device", :foreign_key => "parent_id"
has_many :guests, -> { where type: "Guest" }, :class_name => "Device", :foreign_key => "parent_id"
belongs_to :parent, :class_name => "Device"
has_many :posts
end
With that, you will be able to do server.hosts, etc, which is quite convenient.
Then, you should move each subclass (Server, Host, Guest) to its own file due to Rails loading system. You can try to access the model Server in the console, you will get an undefined error. To fix it, you need to load the model Device, or simply move each subclass in a different file.
Finally, for the routing/controller part, I will advise you to read this post I wrote about common controller for STI resources : http://samurails.com/tutorial/single-table-inheritance-with-rails-4-part-2/.
Note that this is the second part, for more details check out the other articles.

rails 4 how to use foreign key and primary key

How to set the following association:
class Midatum < ActiveRecord::Base
# ..., diagn1, diagn2, diagn3
# sample data:
# ..., "0123", nil ,"0124"
# ..., "0123", nil ,"0124"
# ..., "0123", "1123", nil
belongs_to :icd9, :foreing_key => :diagn1
belongs_to :icd9, :foreing_key => :diagn2
belongs_to :icd9, :foreing_key => :diagn3
end
class icd9 < ActiveRecord::Base
# icd9, description
# sample data:(unique)
#"0123", "some text"
#"0124", "some other text"
#"1123", "description text"
#"1133", "description text"
has_many :midata, :foreing_key => :icd9, :primary_key => :icd9
end
This does not work. It may be obvious for someone but not for me. The database
is a legacy DB and readonly. I need to establish this assoc to able to work with the data.
This answer comes from a Rails expert and it does solve my problem. I am posting it in case someone else have the same problem.
belongs_to :icd9_a, :foreign_key => :diagn1, :class_name => "Icd9"
belongs_to :icd9_b, :foreign_key => :diagn2, :class_name => "Icd9"
belongs_to :icd9_c, :foreign_key => :diagn3, :class_name => "Icd9"
But that means you'll need to query the association using all three methods:
m = Midatum.first
m.icd9_a
m.icd9_b
m.icd9_c
In the same way, over in the Icd9 class you'll need three separate associations with unique names:
class Icd9 < ActiveRecord::Base
self.primary_key = :icd9
has_many :midata_a, :foreign_key => :diagn1, :class_name => "Midatum"
has_many :midata_b, :foreign_key => :diagn2, :class_name => "Midatum"
has_many :midata_c, :foreign_key => :diagn3, :class_name => "Midatum"
end
Note also that since the icd9 table doesn't have an 'id' column but uses the 'icd9' column as the primary key, you'll need to set it as I've done:
self.primary_key = :icd9