On Rails 4. I'm getting some strange errors when I try to load index pages in Active Admin. They were all working fine before, but suddenly I started getting this message (for this example I loaded my Categories index but it is happening for most of them):
NoMethodError in Admin::Categories#index
Showing c:/Ruby200/lib/ruby/gems/2.0.0/bundler/gems/active_admin-3fb7f03335b1/app/views/active_admin/resource/index.html.arb where line #1 raised:
undefined method `validators_on' for Ransack::Search:Class
Extracted source (around line #1):
insert_tag renderer_for(:index)
Application Trace | Framework Trace | Full Trace
config/initializers/form_builder.rb:12:in `label'
I did a search for that method name and it returned only this:
In form_builder.rb
if object.class.validators_on(method).map(&:class).include? ActiveRecord::Validations::PresenceValidator
if options.class != Hash
options = {:class => "required"}
else
options[:class] = ((options[:class] || "") + " required").split(" ").uniq.join(" ")
end
end
I can view the dashboard and individual row pages fine, but when I go to edit a record I get this:
TypeError in Admin::Categories#edit
Showing c:/Ruby200/lib/ruby/gems/2.0.0/bundler/gems/active_admin-3fb7f03335b1/app/views/active_admin/resource/edit.html.arb where line #1 raised:
no implicit conversion of String into Array
Extracted source (around line #1):
insert_tag renderer_for(:edit)
Application Trace | Framework Trace | Full Trace
config/initializers/form_builder.rb:16:in `label'
I have no idea what this means...would it be better to re-install Active Admin/regenerate its assets? Is that a safe thing to do? If so, how do I do that? Or, is there a simple fix to these error messages. Thanks for any help.
I encountered the same issue and have a fix for you. The issue is that the very clever initializer that automatically adds a CSS * to required fields is not compatible with the Ransack search that ActiveAdmin uses. The solution is to check that the model responds_to the necessary method before invoking it:
class ActionView::Helpers::FormBuilder
# http://blog.pothoven.net/2012/10/self-marking-required-fields-in-rails.html
alias_method :orig_label, :label
# add a 'required' CSS class to the field label if the field is required
def label(method, content_or_options = nil, options = nil, &block)
if content_or_options && content_or_options.class == Hash
options = content_or_options
else
content = content_or_options
end
options = add_required_class(options) if presence_required?(method)
orig_label(method, content, options || {}, &block)
end
private
def add_required_class(options)
return { class: 'required' } unless options.class == Hash
new_class = ((options[:class].to_s || '') + ' required')
.split(' ').uniq.join(' ')
options.merge!(class: new_class)
end
def presence_required?(method)
object.class.respond_to?(:validators_on) &&
object.class.validators_on(method).collect(&:class)
.include?(ActiveRecord::Validations::PresenceValidator)
end
end
AA works with Rails 4 and Ruby 2.1.1, however, you have to take AA from the master branch at Github. Please note that AA switched from the "meta_search" gem to "ransack" which is not API-compatible - so some things are sure to break.
Maybe you use custom filters? I had your kind of errors due to custom filters based on scopes since "ransack" does not feature anything like search_method from "meta_search". Here's how I work around this, just in case:
https://github.com/activerecord-hackery/ransack/issues/345
https://github.com/activerecord-hackery/ransack/issues/288
Related
I`m using kaminari in rails 7 to make the apgination of my API, but when i try to see a page different of the first page, im taking a type error, when i try access "http://localhost:3000/products?page=3":
TypeError (no implicit conversion of Symbol into Integer)
My paginated products index:
# GET /products
def index
page_number = params[:page].try(:[], :number)
per_page = params[:page].try(:[], :size)
#products = Product.all.page(page_number).per(per_page)
paginate json: #products
end
Anyone has a clue to how solve this?
EDIT:
I created a initializer named api_pagination.rb and put on him:
ApiPagination.configure do |config|
config.page_param do |params|
params[:page][:number] if params[:page].is_a?(ActionController::Parameters)
end
config.per_page_param do |params|
params[:page][:size] if params[:page].is_a?(ActionController::Parameters)
end
end
And now i can access "http://localhost:3000/products?page%5Bnumber%5D=2&page%5Bsize%5D=12" , but it doesn't look right to me, or this is the right way?
Maybe you need to set default values? Try with:
page_number = params[:page].try(:[], :number) || 1
per_page = params[:page].try(:[], :size) || 20
if that doesn't work, check what's coming in those number and size params or share more information of your issue, like the whole error stacktrace, even better the full request log.
after setup a search into a serializer!
Rails spits out
no implicit conversion of nil into Hash
So, please someone can point out whats wrong with this code?
class SearchController < ApplicationController
def results
results_query = PgSearch.multisearch(params[:q]).paginate(page: page, per_page: 20)
result = results_query.map(&:searchable).map do |result_item|
case result_item.class.name
when 'Post'
PostSerializer.new(result_item)
else
raise NotImplementedError
end
end
render json: {
items: result,
page: page,
pages: results_query.total_pages
}
end
def page
params[:page] || 1
end
def serialize(data, serializer)
ActiveModel::Serializer::CollectionSerializer.new(data, each_serializer: serializer)
end
end
Since your case statement isn't checking many values, you could always make it into a standard if/else statement:
if result_item && result.class.name == 'Post'
PostSerializer.new(result_item)
else
raise NotImplementedError
end
Well, on the screenshots you've provided we can see the log message specifies that the error is on line 5.
According to your code, line 5 is: case result_item.class.name
The error message is TypeError (no implicit conversion of nil into Hash).
You're trying to get the class then the name of result_item. So the problem is with result_item which is equal to nil.
In order the resolve your problem you might want to check the ouput of results_query.map(&:searchable).map.
Based on the screenshot you've provided, I've quickly checked the source code. The offending line seems to be this one: https://github.com/Casecommons/pg_search/blob/master/lib/pg_search/document.rb#L22. The only reason why this would raise the described TypeError is if PgSearch.multisearch_options is nil – which, as far as I understand the code, would only be possible if you accidentally overwrote it in a wrong way. So I'd suggest doublechecking your global setup for PgSearch.multisearch_options to make sure this is actually set.
The east way to check the setting is by using a debugger or putting something like puts PgSearch.multisearch_options or Rails.logger.info 'PgSearch.multisearch_options' into the controller directly above the call that's failing.
So for some odd reason I keep getting this error:
undefined method `>' for nil:NilClass
Rails.root: C:/Sites/booking_saloniser - Calendar
Application Trace | Framework Trace | Full Trace
app/models/user.rb:11:in `block in upcoming_appointments'
app/models/user.rb:11:in `upcoming_appointments'
app/controllers/appointments_controller.rb:8:in `index'
appointment controller
def index
#upcoming_appointments = current_user.upcoming_appointments
end
user model
def upcoming_appointments
appointments.order(appointment_time: :desc).select { |a| a.appointment_time > (DateTime.now) }
end
Any chance someone could help me get around this error?
It appears one or more of your appointment records has a nil appointment_time.
If this is not expected, you should add a validation on the model that it's not null, and fix your existing data.
Otherwise (and this works as quick fix), you can chain a query to not include records with a nil appointment time:
def upcoming_appointments
appointments
.order(appointment_time: :desc)
.where.not(appointment_time: nil)
.select { |a| a.appointment_time > (DateTime.now) }
end
If where.not isn't available (if you're using an older version of rails), you can also use where("appointment_time != null")
I need a def in my application_helper.rb that will accept the model name passed as a variable.
I have a nav view where i am trying to access a particular record based on the content of $current_opportunity
<%# link_to "Lab", lab_path(get_id('Lab')), class: get_labs_class() %>
What I was trying to do was call get_id and pass 'Lab' to it.
My application_helper.rb has
def get_id(model)
model_ids = model.where("opportunity_id = ? ", $current_opportunity)
model_ids = model_ids.first
model_id = model_ids.id
model_id = model_id.to_i
return model_id
end
If I try to run like that, I get
NoMethodError in Prospects#show
Showing C:/Users/cmendla/RubymineProjects/product_development/app/views/shared/_tabs_nav.html.erb where line #61 raised:
undefined method `where' for "Lab":String
Trace of template inclusion: app/views/layouts/application.html.erb
Rails.root: C:/Users/cmendla/RubymineProjects/product_development
Application Trace | Framework Trace | Full Trace
app/helpers/application_helper.rb:25:in `get_id'
app/views/shared/_tabs_nav.html.erb:61:in `_app_views_shared__tabs_nav_html_erb__956794461_83328552'
app/views/layouts/application.html.erb:113:in `_app_views_layouts_application_html_erb___468328524_46368744'
However, if I change the def to
model_ids = Lab.where("opportunity_id = ? ", $current_opportunity)
i.e hard wiring Lab, everything works.
Is there any way to substitute the value of model in the where statement?
Try:
model_ids = model.constantize.where("opportunity_id = ? ", $current_opportunity)
constantize also works with symbols
I am running a spree app.
I am getting below error when I try to add any product in the cart.
undefined method `+' for nil:NilClass
This error comes only when I add option types and variants of the same product.
I am not sure what's exactly going wrong here, because I am not doing any changes in the code or something.
This is the extracted source it shows.
if quantity.between?(1, 2_147_483_647)
begin
order.contents.add(variant, quantity, options)
rescue ActiveRecord::RecordInvalid => e
error = e.record.errors.full_messages.join(", ")
end
Here's my order controller's populate function.
# Adds a new item to the order (creating a new order if none already exists)
def populate
order = current_order(create_order_if_necessary: true)
variant = Spree::Variant.find(params[:variant_id])
quantity = params[:quantity].to_i
options = params[:options] || {}
# 2,147,483,647 is crazy. See issue #2695.
if quantity.between?(1, 2_147_483_647)
begin
order.contents.add(variant, quantity, options)
rescue ActiveRecord::RecordInvalid => e
error = e.record.errors.full_messages.join(", ")
end
else
error = Spree.t(:please_enter_reasonable_quantity)
end
if error
flash[:error] = error
redirect_back_or_default(spree.root_path)
else
respond_with(order) do |format|
format.html { redirect_to cart_path }
end
end
end
Please help me out here.
You need to ensure the values of variant, quantity and options before sending them to spree.
The fact that you get this error could be considered as a bug on their side, since you'd expect a nice error message saying "variant is nil" or the like.
To fix your problem though, I'd check that these values are valid ones before sending them to spree.
For future views about this issue.
Check if the Variant cost_currency attribute is the same that is configured in Spree. You can check it in a rails console doing:
Spree::Config.get(:currency)
Sometimes it happens when spree is initialized with some currency by default and then the default currency is changed.