ActiveAdmin - can't create model "Rating" - ruby-on-rails

I have no idea why I get the error when I click on "New Rating". And it seems creation of other models gives the same error.
Here's the error msg: "no member 'rating' in struct"
The error is on line 316 of inherited_resources-1.4.0/lib/inherited_resources/base_helpers.rb
Full stacktrace: https://gist.github.com/depy/5330548
313 # extract attributes from params
314 def build_resource_params
315 parameters = respond_to?(:permitted_params) ? permitted_params : params
316 rparams = [parameters[resource_request_name] || parameters[resource_instance_name] || {}]
317 if without_protection_given?
318 rparams << without_protection
319 else
320 rparams << as_role if role_given?
321 end
Here's my Rating model:
class Rating < ActiveRecord::Base
validates_uniqueness_of :task_id, :scope => [:user_id, :user_role], :message => 'You have already rated this task'
validates_inclusion_of :user_role, :in => %w( client contractor )
validates_presence_of :task_id, :user_id
validates_presence_of :score, :message => 'Please rate your satisfaction'
belongs_to :task
belongs_to :user
end
Here's my ActiveAdmin Rating.rb:
ActiveAdmin.register Rating do
controller do; include StrongAdmin; end
# list
index do
column :user_id
column :task_id
column :comment
column :score
default_actions
end
# single
show do |rating|
attributes_table do
row :id
row :rater do
task_id = Rating.find(params[:id]).task_id
div do
Task.find(task_id).client.full_name + " [" + Task.find(task_id).client.id.to_s+"]"
end
end
row :user
row :user_role
row :task
row :score
row :comment
row :created_at
end
active_admin_comments
end
end
Here's my Gemfile:
source 'https://rubygems.org'
ruby "1.9.3"
gem 'rails'
gem 'pg' # Database (PostgreSQL)
group :assets do
gem 'sass-rails'
gem 'uglifier'
gem 'bourbon'
gem 'jquery-fileupload-rails'
gem 'jquery-rails'
gem 'asset_sync'
end
group :production do
gem 'honeybadger'
gem 'newrelic_rpm' # App monitoring
end
gem 'bcrypt-ruby' # Secure passwords
gem 'devise' # Authentication
gem 'unicorn' # Webserver
gem 'redis'# Session storage and Task applications
gem 'carrierwave' # File uploading
gem 'mini_magick' # Image processing
gem 'kaminari'# Pagination
gem 'turbolinks' # Pushstate and async loading
gem 'strong_parameters' # Attribute accessible replacement
gem 'dalli' # Memcached interface
gem 'fog' # CDN connector
gem 'activeadmin' # (user) administration
gem 'cancan' # Authorization
gem 'gibbon' # Mailchimp API wrapper
gem 'multi_json'
gem 'nokogiri' # HTML parser for error messages
gem 'pusher' # Hosted websockets
gem 'sidekiq' # Async processing
gem 'draper' # Decorator
gem 'lograge' # Improved logger
gem 'slim'
gem 'sinatra', :require => nil
group :development do
gem 'sqlite3'
gem 'better_errors'
gem 'binding_of_caller'
gem 'meta_request'
gem 'quiet_assets'
end
group :test, :darwin do
gem 'rb-fsevent'
end
group :test do
gem 'rspec-rails'
gem 'factory_girl_rails'
gem 'capybara'
# gem 'capybara-webkit'
gem 'database_cleaner'
gem 'launchy'
gem 'faker'
end

I encountered the same issue. I updated ActiveAdmin from 0.5.1. to 0.6.0. The inherited resource gem was also updated to 1.4.0.
Since ActiveAdmin requires 1.3.1 or higher, you can lock the version in your gem
gem 'inherited_resources', "1.3.1"
This solved the issue for me.

Related

While using rspec i am constantly getting the same error

I am getting the same Error on running rspec that is :-
"Undefined Method - authorize_manage_partner_links"
I am using CANCAN gem in my Gemfile for authorization purposes and i am using Rails version 3.2 and Ruby version 1.9.2.
Please suggest what to do as i am totally new to rspec and rails. I am using a testing database, on importing the database for the first time, when i am running rspec it is showing successful but after that it is showing this error on running the same rspec file. I am using FactoryGirl. and i have defined everything in my factoryrb file as well.
This is my controller--
require 'will_paginate/array'
class PartnerLinksController < ApplicationController
#load_and_authorize_resource
before_filter :authorize_manage_partner_links!
layout "backoffice"
def index
#partner_links = PartnerLink.all
if params[:sortby]
#partner_links = #partner_links.sort_by {|p| p.name} if params[:sortby] == "up"
#partner_links = #partner_links.sort_by {|p| p.name}.reverse if params[:sortby] == "down"
else
#partner_links = #partner_links.sort_by {|p| p.name}
end
total = #partner_links.size
#partner_links = #partner_links.paginate(:page => params[:page], :per_page => 20)
page = params[:page]
if !page
page = 1
end
render :locals => {:total => total, :page => page, :sortby => params[:sortby], :partner_link => #partner_link}
end
def new
#partner_link = PartnerLink.new
end
def edit
#partner_link = PartnerLink.find(params[:id])
end
def create
#partner_link = PartnerLink.new(params[:partner_link])
if #partner_link.save
redirect_to partner_links_url
else
render "new"
end
end
def update
#partner_link = PartnerLink.find(params[:id])
if #partner_link.update_attributes(params[:partner_link])
redirect_to partner_links_url
else
render "edit"
end
end
def destroy
#partner_link = PartnerLink.find(params[:id])
#partner_link.destroy
redirect_to partner_links_url
end
end
This is my rspec controller that i am using--
require 'spec_helper'
describe PartnerLinksController do
before do
FactoryGirl.create(:partner_link)
role_permission
admin_role
user
currency
category
merchant
cart
deal
sign_in user
end
let(:role_permission) {FactoryGirl.create(:role_permission)}
let(:currency) {FactoryGirl.create(:currency)}
let(:merchant) {FactoryGirl.create(:merchant)}
let(:cart) {FactoryGirl.create(:cart)}
let(:deal) {FactoryGirl.create(:deal)}
let(:category) {FactoryGirl.create(:category)}
let(:authentication) {FactoryGirl.create(:authentication)}
let(:user) {FactoryGirl.create(:user)}
let(:admin_role) {FactoryGirl.create(:admin_role)}
describe "index" do
it "Should display all the partner links" do
get :index
end
end
describe "new" do
it "Should create all the partner links" do
get :new
end
end
describe "create" do
it "Should create new all the partner links" do
get :create
end
end
describe "update" do
it "Should update all the partner links" do
get :update
end
end
describe "destroy" do
it "Should delete all the partner links" do
get :destroy
end
end
end
app/models/partner_link.rb--
class PartnerLink < ActiveRecord::Base
# attr_accessible :title, :body
validates_presence_of :name, :url, :description
end
This is my Gemfile--
source 'http://rubygems.org'
ruby '1.9.2'
gem 'rails', '3.2.11'
gem 'authlogic'
gem "devise"
gem "devise-encryptable"
gem "devise-async"
gem 'omniauth'
gem 'omniauth-facebook'
gem 'omniauth-twitter'
gem "cancan"
gem 'activemerchant'
gem 'aws-sdk'
gem 'aws-s3'
gem 'paperclip', '~> 3.0'
gem 'oauth2'
#gem 'fastercsv' #no-longer required after ruby 1.9
gem 'pg'
#gem 'thin'
gem 'unicorn'
gem 'simple_form'
gem 'haml-rails' # Use HAML instead of ERB for templates
gem 'friendly_id'
gem 'will_paginate'
gem 'will_paginate-bootstrap'
gem "nifty-generators", :group => :development
#gem "pdfkit"
gem "pdfkit", "~> 0.5.0"
gem 'wkhtmltopdf-binary'
gem 'wicked_pdf'
gem 'sendgrid', "~> 1.0.1"
gem 'delayed_job'
gem 'delayed_job_active_record'
gem 'bootstrap-datepicker-rails'
#gem 'roadie' #fixing email css
group :development, :test do
gem 'rspec-rails'
gem 'guard-rspec'
# Database Cleaner clears the database between tests. This done because we have
# to set config.use_transactional_fixtures = false in the spec_helper file.
# The use_transactional_fixtures value is set to false because Selenium test
# driver cannot access the test records created via database transactions.
gem 'database_cleaner'
end
group :test do
# gem 'factory_girl_rails'
gem 'capybara'
# As we’re using Capybara we can call the save_and_open_page method at any
# point and this will open the page in a browser so that we can take a look
# at it. This is enabled by Launchy.
# gem 'launchy'
# gem 'rspec-mocks'
end
gem "less-rails"
gem 'twitter-bootstrap-rails', '>= 2.0.3'
gem 'rb-readline', '~> 0.5.0', require: 'readline'
gem 'execjs'
gem 'therubyracer'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', " ~> 3.2.3"
gem 'coffee-rails', "~> 3.2.1"
gem 'uglifier', '>= 1.0.3'
end
gem "mail", "~> 2.4.4"
gem 'jquery-rails'
#gem "mocha", :group => :test
gem 'gmaps4rails'
gem 'acts_as_xlsx'
gem "httparty"
gem 'newrelic_rpm'
gem 'font_assets'
gem 'paper_trail', '~> 3.0.6'
gem 'mailchimp-api', require: 'mailchimp'
gem 'rack-ssl-enforcer'
gem 'ckeditor'
gem "rails_best_practices"

ActiveModel Serializers: How do I serialize a resource collection?

I have a bookmarks resource and have mapped it to serve json by default under my api namespace like so in my routes.rb:
namespace :api, defaults: {format: 'json'} do
resources :bookmarks
get ':username', to: 'users#index'
get ':username/bookmarks/:id', to: 'users#show'
end
I have a Api::UsersController controller and a supporting BookmarkSerializer that works just fine on an individual bookmark resource like http://localhost:3000/api/emma_carter/bookmarks/87
But when I try to hit http://localhost:3000/api/emma_carter which is supposed to serve all bookmarks owned by the user, I get all different kinds of errors. Here is my Api::UsersController
module Api
class UsersController < ApplicationController
respond_to :json
def index
user = User.find_by(username: params[:username])
bookmarks = user.bookmarks
render json: bookmarks
end
def show
user = User.find_by(username: params[:username])
bookmark = user.bookmarks.find_by(params[:id])
render json: bookmark
end
end
end
The show method works but the index method gives me ArgumentError in Api::UsersController#index
wrong number of arguments (1 for 0)
UPDATE: Full stack trace here: https://gist.github.com/amite/b79fc42bfd73de5a07bd
screenshot
Here is the serializer:
class BookmarkSerializer < ActiveModel::Serializer
attributes :id, :url, :title, :domain, :notes, :image, :created, :username
belongs_to :user
def created
object.created_at
end
def username
user.username
end
end
Looking at other solutions on stack overflow, I have also tried other versions of my index method:
def index
user = User.find_by(username: params[:username])
bookmarks = user.bookmarks
bookmarks.map { |bookmark| ::BookmarkSerializer.new(bookmark)}.to_json #updated line
end
This gives me the error:
Missing template api/users/index, application/index with {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}.
Next the last version of my index method looks like this:
def index
user = User.find_by(username: params[:username])
bookmarks = user.bookmarks
ActiveModel::ArraySerializer.new(bookmarks, each_serializer: ::BookmarkSerializer).to_json
end
This gives me the error uninitialized constant ActiveModel::ArraySerializer
What am I doing wrong? I am using rails 4.1.5 and the github version of the active_model_serializers
gem.
gem 'active_model_serializers', github: 'rails-api/active_model_serializers'
UPDATE: Since I am trying to output a collection of bookmarks I also tried using a separate serializer
BookmarksSerializer but I am getting the same error: ArgumentError in Api::UsersController#index
wrong number of arguments (1 for 0)
UPDATE2: Here is a version of the index method that kinda works in the sense that it renders the resource collection in json format:
def index
user = User.find_by(username: params[:username])
bookmarks = user.bookmarks
respond_with bookmarks.to_json
end
But this still does not use the BookmarksSerializer
class BookmarksSerializer < ActiveModel::Serializer
attributes :id, :title
end
It just outputs the default hash
Full Gemfile
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.5'
# Use mysql as the database for Active Record
gem 'mysql2'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
gem 'bourbon'
gem 'neat'
gem 'bitters'
gem 'refills'
gem 'wisper'
gem 'rails-ioc'
gem 'reform'
gem 'cells'
gem "pundit"
gem 'active_model_serializers', github: 'rails-api/active_model_serializers'
gem "font-awesome-rails"
gem 'simple_form'
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
group :development, :test do
# Call 'debugger' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
gem 'ffaker'
gem 'pry-rails'
gem 'capybara'
gem 'factory_girl_rails'
gem 'database_cleaner'
gem 'capybara-webkit'
gem 'rspec-cells'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-commands-rspec'
gem 'rspec-rails'
gem 'guard-rspec'
gem 'rb-fsevent' if `uname` =~ /Darwin/
end
# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'
# Use unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Use debugger
# gem 'debugger', group: [:development, :test]
turns out I need to include v0.9 of the gem
gem 'active_model_serializers', github: 'rails-api/active_model_serializers', branch: '0-9-stable'
you could try change:
def index
user = User.find_by(username: params[:username])
bookmarks = user.bookmarks
bookmarks.map { |bookmark| ::BookmarkSerializer.new(bookmark)}.to_json #updated line
end
to:
def index
user = User.find_by(username: params[:username])
bookmarks = user.bookmarks
render json: bookmarks.map { |bookmark| ::BookmarkSerializer.new(bookmark)}
end

undefined method `scan' for {"tooth"=>""}:Hash

I upgraded to rails4 from 3.2.2 and i now get this undefined method from my rabl template that id didn't get before the upgrade.
the "tooth" paramater on procedures is a set by a getter/setter method that is stored in the postgres database as a hstore hash named properties.
Not sure what has changed in rails4 to make this happen!
Any help would be much appreciated.
ERROR:
Showing /home/action/app/views/procedures/chart.json.rabl where line #1 raised:
undefined method `scan' for {"tooth"=>""}:Hash
Extracted source (around line #1):
1 object #procedures
2 attributes :buccal, :mesial, :occlusal, :distal, :lingual
Trace of template inclusion: app/views/procedures/_procedures_table.html.erb, app/views/procedures/chart.html.erb
Procedures model (getter and setter method for :tooth)
%w[tooth buccal mesial occlusal distal lingual].each do |key|
attr_accessible key
scope "has_#{key}", lambda { |value| where("properties #> (? => ?)", key, value) }
define_method(key) do
properties && properties[key]
end
define_method("#{key}=") do |value|
self.properties = (properties || {}).merge(key => value)
end
end
Gemfile:
source 'http://rubygems.org'
gem 'rails', '4.0.0.rc2'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'pg'
gem "paperclip", "~> 3.0"
gem 'rabl'
gem 'activerecord-postgres-hstore'
gem "bugsnag"
gem 'country_select'
gem 'bullet', group: :development
# Asset template engines
gem 'sass-rails', '~> 4.0.0.rc1'
gem 'coffee-rails', '~> 4.0.0.rc1'
gem 'uglifier', '>= 1.3.0'
gem 'twitter-bootstrap-rails'
gem 'therubyracer', :platform => :ruby
gem 'less-rails'
gem 'jquery-ui-rails'
gem 'jquery-rails'
# Use unicorn as the web server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'ruby-debug19', :require => 'ruby-debug'
# Declarative Authorization
gem 'declarative_authorization'
gem 'protected_attributes'
# Authlogic
gem 'authlogic'
gem 'simple_form', '3.0.0.rc'
group :production do
end
group :test do
# Pretty printed test output
gem 'turn', :require => false
end
gem 'rubber'
gem 'open4'
gem 'gelf'
gem 'graylog2_exceptions', :git => 'git://github.com/wr0ngway/graylog2_exceptions.git'
gem 'graylog2-resque'
Found the answer!! Rails 4 now has native support for Hstore, which is awesome but I hadn't realised. To fix my problem i merely followed this guide below which is great to set up my model with hstore and then deleted my getter/setter methods. http://blog.remarkablelabs.com/2012/12/a-love-affair-with-postgresql-rails-4-countdown-to-2013

Rails 3.2.8 Actionmailer - stack level too deep PLUS uninitialized constant Mail::Ruby19

I'm following a tutorial referenced in a StackOverflow post for a simple contact form. Tutorial is here: http://matharvard.ca/posts/2011/aug/22/contact-form-in-rails-3/
Everything is copy/paste and change a few values for my domain and mail settings. Running into two very strange errors: When I first submit the contact form, I get a :
stack level too deep
Rails.root: /Users/me/application
Application Trace | Framework Trace | Full Trace
This error occurred while loading the following files:
mail
mail/parsers/rfc2822_obsolete
If I resubmit without restarting the rails app, I get:
uninitialized constant Mail::Ruby19
Rails.root: /Users/me/application
Application Trace | Framework Trace | Full Trace
app/mailers/notifications_mailer.rb:1:in `'
app/controllers/contact_controller.rb:11:in `create'
This error occurred while loading the following files:
mail
The sections I feel might be relavent are:
class NotificationsMailer < ActionMailer::Base
default :from => "feedback#mydomain.com"
default :to => "me#gmail.com"
def new_message(message)
#message = message
mail(:subject => "mydomain Feedback")
end
end
class Message
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :name, :email, :subject, :body
validates :name, :email, :subject, :body, :presence => true
validates :email, :format => { :with => %r{.+#.+\..+} }, :allow_blank => true
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
class ContactController < ApplicationController
def new
#message = Message.new
end
def create
#message = Message.new(params[:message])
if #message.valid?
NotificationsMailer.deliver_new_message params[:message]
# NotificationsMailer.new_message(#message).deliver
redirect_to(root_path, :notice => "Message was successfully sent.")
else
flash.now.alert = "Please fill all fields."
render :new
end
end
end
The rest of the templates are very straightforward and rendering fine.
Also, attaching the gemfile in case I missed some obvious conflict in there:
source 'https://rubygems.org'
gem 'rails', '3.2.8'
gem 'sqlite3'
gem 'redis', '2.1.1'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
gem 'jade'
gem "haml", ">= 3.1.7"
gem "haml-rails", ">= 0.3.5", :group => :development
gem "hpricot", ">= 0.8.6", :group => :development
gem "ruby_parser", ">= 2.3.1", :group => :development
gem "rspec-rails", ">= 2.11.4", :group => [:development, :test]
gem "email_spec", ">= 1.2.1", :group => :test
gem "cucumber-rails", ">= 1.3.0", :group => :test, :require => false
gem "database_cleaner", ">= 0.9.1", :group => :test
gem "launchy", ">= 2.1.2", :group => :test
gem "capybara", ">= 1.1.2", :group => :test
gem "factory_girl_rails", ">= 4.1.0", :group => [:development, :test]
gem "bootstrap-sass", ">= 2.1.0.1"
gem "devise", ">= 2.1.2"
gem "cancan", ">= 1.6.8"
gem "rolify", ">= 3.2.0"
gem "simple_form", ">= 2.0.4"
gem "quiet_assets", ">= 1.0.1", :group => :development
gem "hub", ">= 1.10.2", :require => nil, :group => [:development]
gem 'paperclip'
gem 'aws-sdk'
gem 'aws-s3'
gem "high_voltage"
Thank you in advance.
I think the following code from ContactController.rb is the culprit:
NotificationsMailer.deliver_new_message params[:message]
You do not actually have a method name deliver_new_message
Try removing it, and uncommenting the line below it:
NotificationsMailer.new_message(#message).deliver
Hope this helps

Spree admin panel not working

I've install Spree gem and run it as it wrote in Getting Started. All works fine but if I want to go in the Products section in admin panel I have the following error:
Mysql2::Error: Unknown column 'variants.position' in 'order clause': SELECT `variants`.* FROM `variants` WHERE (`variants`.product_id IN (706676762,569012001,723959550,1025786064,1060500592,248786582,187438981,1035865702,459084718) AND (variants.is_master = 0 AND variants.deleted_at IS NULL)) ORDER BY variants.position ASC
Anyone faced that?
EDIT: Here is my Gemfile
source 'http://rubygems.org'
gem 'rails', '3.0.7'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'mysql2', '~> 0.2.11'
gem 'heroku'
gem 'thin'
gem 'spree', '~> 0.60.0'
# Use unicorn as the web server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+)
# gem 'ruby-debug'
# gem 'ruby-debug19', :require => 'ruby-debug'
# Bundle the extra gems:
# gem 'bj'
# gem 'nokogiri'
# gem 'sqlite3-ruby', :require => 'sqlite3'
# gem 'aws-s3', :require => 'aws/s3'
# Bundle gems for the local environment. Make sure to
# put test-only gems in this group so their generators
# and rake tasks are available in development mode:
# group :development, :test do
# gem 'webrat'
# end
gem "test", :path => "test", :require => "test"
Normally when you install spree by following these steps, you should have some migration files inside db/migrate, one of them contain the missing column for your application :
class AddPositionToVariants < ActiveRecord::Migration
def self.up
add_column :variants, :position, :integer
end
def self.down
remove_column :variants, :position
end
end

Resources