<main>': uninitialized constant ActiveRecord (NameError) - ruby-on-rails

I have the following model in my Rails 3.2.13 build. I am trying to use it to insert data into my database.
class Financials < ActiveRecord::Base
#attr_accessible :description, :stock
attr_accessible :symbol, :cur_price
sym = Financials.new(:symbol => test, :cur_price => 10)
sym.save
end
but when I try to run the code I get the following error:
financials.rb:1:in `': uninitialized constant ActiveRecord (NameError)
I checked through SO and found others that had similar errors and they suggested that I add entries in the environment.rb ruby on rails pluralization help?
I added the following to the environment.rb file:
Inflector.inflections do |inflect|
inflect.irregular 'financialss', 'financials'
end
but it did resolve my issue. Thanks in advance

You don't create new objects inside the definition of the model. You should be doing this in the create action of the controller.
Given your model:
class Financial < ActiveRecord::Base
attr_accessible :symbol, :cur_price
# validations, methods, scope, etc.
end
You create the new Financial object in your controller and redirect to the appropriate path:
class FinancialsController < ApplicationController
def create
#financial = Financial.new(params[:financial])
if #financial.save
redirect_to #financial
else
render :new
end
end
def new
#financial = Financial.new
end
def show
#financial = Financial.find(params[:id])
end
end

Related

undefined method `table_name' for Post:Module Did you mean? table_name_prefix

I'm building an API with the kollegorna's tutorial.
I used ActiveHashRelation for displays serialiazed arrays properly.
# app/controllers/api/v1/posts_controller.rb
class Api::V1::PostsController < Api::V1::BaseController
include ActiveHashRelation
def index
posts = apply_filters(Post::Post.all, params)
render json: posts, each_serializer: Api::V1::PostSerializer
end
end
The problem is that I have a model Post::Post and the module Post. It's like it can not found the correct model.
# app/models/post/post.rb
class Post::Post < ActiveRecord::Base
validates_presence_of :body
end
# app/models/post.rb
module Post
def self.table_name_prefix
'post_'
end
end
I think it's because of ActiveHashrelation because when I write posts = Post::Post.all it's working. But I can't filter the array.

The correct way to do inheritance in Rails mountable engine

Today, I found a very strange issue while writing a mountable engine using Rails 3.
I have the following ApplicationController in my engine:
module Marketplace
class ApplicationController < ::ApplicationController
before_filter :merge_abilities
layout 'marketplace/application'
def marketplace_current_user
Marketplace::User.find(current_user.id)
end
private
def merge_abilities
current_ability.merge(Ability.new(current_user))
end
end
end
And my User model definition is
module Marketplace
class User < ::User
devise omniauth_providers: [:facebook, :paypal]
has_one :payout_identity, class_name: "Marketplace::PayoutIdentity"
has_many :course_purchases, class_name: "Marketplace::CoursePurchase"
def has_verified_payout_identity?
self.payout_identity and self.payout_identity.receiver_id
end
end
end
After starting up the rails server, the first request to load a page will have the controller run the marketplace_current_user method correctly and load the engine's User class. However any request after the first one will given a strange NameError - "uninitialized constant Marketplace::Marketplace::User".
I tried removing the namespace in marketplace_current_user definition but it will load the main app's User class instead.
At last when I change my ApplicationController to look like this:
class Marketplace::ApplicationController < ::ApplicationController
before_filter :merge_abilities
layout 'marketplace/application'
def marketplace_current_user
Marketplace::User.find(current_user.id)
end
private
def merge_abilities
current_ability.merge(Ability.new(current_user))
end
end
Everything would work fine.
Could someone enlighten me where I got it wrong at the beginning? Was it wrong to do inheritance that way?

Friendly_id and Active Admin conflict - possibly because of revert_freindly_id

first time asking a question on stack overflow :)
I'm having a conflict between friendly_id and active admin (it's an assumption), as discussed in many threads here. I've looked at all those threads, but I'm not entirely sure they solve my problem. Sorry for the really long post!
I'm trying to create friendly links to products on my website. I've added the friendly_id gem and everything works fine in my dev and staging environments, but friendly links fail on production. Here is all my code:
Model:
class Product < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: :slugged
...
end
Controller:
class ProductsController < ApplicationController
before_filter :get_product, only: [:show]
...
private
def get_product
#product = Product.friendly.find(params[:id])
end
end
All my product records have a completed slug field at this point. I don't want to use slugs in my admin interface, so when I came across a solution here, I went ahead and modified it a bit to get active admin to work together with friendly_id.
config/initializers/active_admin.rb:
ActiveAdmin.setup do |config|
...
config.before_filter :revert_friendly_id
end
I've defined revert_friendly_id in the application controller:
class ApplicationController < ActionController::Base
...
protected
def revert_friendly_id
model_name = self.class.name.match(/::(.*)Controller$/)[1].singularize
# Will throw a NameError if the class does not exist
Module.const_get model_name
eval(model_name).class_eval do
def to_param
id.to_s
end
end
rescue NameError
end
end
I've noticed that when I first deploy to production via capistrano, the friendly links work as expected. So my product links are accessible with: http://website.com/products/my-product-slug. But the minute I access the admin interface on production, the links immediately switch back to product ids instead: http://website.com/products/12345. I'm not entirely sure how to resolve this problem, though I understand why it might be happening, can someone help me please?
Here is how I solved the problem. Based on armstrjare's fix at this link.
I removed the revert_friendly_id function from my application controller and the before_filter from my config. Then just added the following to app/admin/product.rb:
ActiveAdmin.register Product do
around_filter do |controller, action|
Product.class_eval do
alias :__active_admin_to_param :to_param
def to_param() id.to_s end
end
begin
action.call
ensure
Product.class_eval do
alias :to_param :__active_admin_to_param
end
end
end
...
end
And everything worked as expected. Hope this helps someone else!
I found a very simple solution: Just overwrite the to_param in your model and check if it is called from active_admin.
app/models/product.rb:
class Product < ActiveRecord::Base
def to_param
if caller.to_s.include?"active_admin"
id && id.to_s
else
slug
end
end
end
When you set the to_param method, it will be set on the entire application. So you have to check if the requested controller is in the Admin namespace or not. Based on that you have to switch back the return of the to_param method.
You can redefine find_resource method in controller:
controller do
def find_resource
scoped_collection.friendly.find(params[:id])
end
end
For the active_admin belongs_to association you can to use the finder: option (from https://github.com/activeadmin/inherited_resources/blob/master/lib/inherited_resources/belongs_to_helpers.rb#L17)
For example:
belongs_to :content, finder: :find_by_slug!

undefined local variable or method `current_order'

I created a new model named PaypalOrder using:
rails generate model order_id:integer ip_address:string first_name:string last_name:string card_type:string card_expires_on:date
Then I ran rake db:migrate
Now my order model looks like:
class PaypalOrder < ActiveRecord::Base
belongs_to :order
attr_accessor :card_number, :card_verification
validate :validate_card, :on => :create
def purchase
#code
end
private
def validate_card
#code
end
def credit_card
#code
end
end
and the controller i created:
class PaypalOrdersController < ApplicationController
def new
#paypal_order = PaypalOrder.new
end
def create
#paypal_order = current_order.build_paypal_order(params[:paypal_order])
if #paypal_order.save
# ...
else
render :action => "new"
end
end
end
But I'm getting the following error:
NameError in PaypalOrdersController#create
undefined local variable or method `current_order' for #<PaypalOrdersController:0xf7b0a34>
Why am I not able to access the current_order and how can I successfully build paypal_order
EDIT: made the following change:
class PaypalOrdersController < Spree::BaseController
works fine now!!
Why not change line 8 of your controller to:
#paypal_order = PaypalOrder.new(params[:paypal_order])
?
If it is Rails 4 you'll have to do:
#paypal_order = PaypalOrder.new(params.require(:paypal_order).permit!)
As per the error, current_order method does not exist.
You need to create current_order method first before calling it.
I am assuming that your intention with current_order was to reuse the order instantiated by the new action...
Since instance variables don't live through more than one request you need to instantiate the paypalorder again.
#paypal_order = PaypalOrder.new(params[:paypal_order])
enter code here

NameError in Rails 3

So I'm trying out the Public Activity gem for a notification timeline and I don't understand why I'm getting the NameError , uninitialized constant message.
Here's the error I'm getting:
NameError in ActivitiesController#index
uninitialized constant ActivitiesController::PublicActivity
app/controllers/activities_controller.rb:3:in `index'
uninitialized constant ActivitiesController::PublicActivity
Here's my controller code where the error is said to be:
class ActivitiesController < ApplicationController
def index
#activities = PublicActivity::Activity.order("created_at desc")
end
end
I'm trying this out based on a rails cast: http://railscasts.com/episodes/406-public-activity
And as far as I know I've done the same thing as the one on it.
There isn't any activity model, but here's the post and comments model where I used the PublicActivity module:
POST MODEL:
class Post < ActiveRecord::Base
include PublicActivity::Model
tracked
COMMENT MODEL
class Comment < ActiveRecord::Base
include PublicActivity::Model
tracked
belongs_to :post
belongs_to :user
end
according to gem sources
def load_orm
require "public_activity/orm/#{##orm.to_s}"
m = "PublicActivity::ORM::#{##orm.to_s.classify}".constantize
::PublicActivity.const_set(:Activity, m.const_get(:Activity))
::PublicActivity.const_set(:Adapter, m.const_get(:Adapter))
::PublicActivity.const_set(:Activist, m.const_get(:Activist))
::PublicActivity.const_set(:Trackable, m.const_get(:Trackable))
end
You should use next code
#activities = ::PublicActivity::Activity.order("created_at desc")
Also ensure that you installed gem with bundle, check bundle show public_activity

Resources