has_scope gem and datatable: undefined method `apply_scopes' - ruby-on-rails

I would like to use the has_scope gem for filtering results of a datatable that is created using Ajax-Datatable-Rails gem.
my controller renderer:
render json: NotesDatatable.new(params, user: current_user, team_ids: #my_colleagues, view_context: view_context, notes_load_all: notes_load_all)
In my notes_datatable.rb:
I call the include HasScope
I add the delegators: def_delegators :#view, :check_box_tag, :has_scope,:apply_scopes
I add scopes parameters for the model: has_scope :by_user_ids
I then create a get_raw_records method:
def get_raw_records
query = apply_scopes(Notes.all)
query
end
This is where the error pops, I get the following:
NoMethodError (undefined method `apply_scopes' for #<#<Class:0x00007fb79c507070>:0x00007fb76e3f80b8>
112 module Forwardable
193 def self._delegator_method(obj, accessor, method, ali)
216 end
218 _compile_method("#{<<-"begin;"}\n#{<<-"end;"}", __FILE__, __LINE__+1)
219 begin;
❯ 228 end;
229 end
230 end
):
There is not much documented about this approach, I found this link, where one user uses this approach.
Can someone help me please ?

Related

NameError uninitialized constant JobsController::Pagination using no gems in Ruby

Using Rails 6.1.6 and Rails 2.7.0. and am following an article for adding pagination in Ruby using no gems. I'm running into a NameError exception for my Pagination module. Not certain if the naming of the hierarchy in the module is incorrect.
Pagination Helper
module PaginationHelper
def paginate(collection:, params: {})
pagination = Services::Pagination.new(collection, params)
[
pagination.metadata,
pagination.results
]
end
end
Jobs Controller
class JobsController < ApplicationController
include Pagination
JOBS_PER_PAGE = 8
def index
#pagination, #jobs = paginate(collection: Job.all, params: page_params)
end
Error Message
NameError Exception
I've tried restarting the server to no avail. Am I missing something in the Pagination module?
That should be include PaginationHelper in your controller.
Or rename the helper to module Pagination.

Rubymine command + click shows Rails methods but Not ruby methods. is it possible to command + click Ruby methods in a rails app?

So I'll have something like...
MyClassname.find_by_name("email")
If I command + click find_by_name my rubymine tells me "method_missing" as it is not a RAILS method, It's a method in Ruby. So Is it possible to configure my Rubymine to navigate to BOTH rails and ruby methods?
Your MyClassname::find_by_name is Rails method, not pure Ruby method. But it is defined dynamically
And yes, this method is really missing :) This way it works
I think that it is worth mentioning this in more detail to make it clearer
Please look example in Ruby docs:
https://ruby-doc.org/core/BasicObject.html#method-i-method_missing
class Roman
def roman_to_int(str)
# ...
end
def method_missing(symbol, *args)
str = symbol.id2name
begin
roman_to_int(str)
rescue
super(symbol, *args)
end
end
end
r = Roman.new
r.iv #=> 4
r.xxiii #=> 23
r.mm #=> 2000
r.foo #=> NoMethodError
You can define method method_missing in your class, catch error there and make what you want
In Rails these methods are defined metaprogrammatically
Please look in Rails source:
https://github.com/rails/rails/blob/main/activerecord/lib/active_record/dynamic_matchers.rb
This module realized method_missing method as in Ruby docs
def method_missing(name, *arguments, &block)
match = Method.match(self, name)
if match && match.valid?
match.define
send(name, *arguments, &block)
else
super
end
end
And dynamically defines methods
def define
model.class_eval <<-CODE, __FILE__, __LINE__ + 1
def self.#{name}(#{signature})
#{body}
end
CODE
end
private
def body
"#{finder}(#{attributes_hash})"
end
def signature
attribute_names.map { |name| "_#{name}" }.join(", ")
end
So you can use find_by as prefix and attribute name as suffix
MyClassname.find_by_id(3)
And even you can find record using few arguments
MyClassname.find_by_id_and_name(3, 'name')
And as using classic find_by, you can raise exception if record is not found using bang
MyClassname.find_by_id!(3)
But RubyMine is not so smart and it doesn't use Ruby interpreter to check presence of dynamic methods so that's why you just see method_missing
In my opinion, using the classic find_by method in code is more transparent and understandable than using a metaprogrammatical suffixes

Rails Active Model Serializer - Custom Serializer on AMS 0.10 - group_by

I have updated active_model_serializer from 0.9.3 to 0.10.0 as I want to use the json_api adapter. Once updated, I no longer can use both my model serializer along with my custom serializer. Here's my backtrace:
[active_model_serializers] Rendered GroupedProjectsSerializer with
ActiveModelSerializers::Adapter::JsonApi (6.03ms)
Completed 500 Internal Server Error in 24ms (ActiveRecord: 0.3ms)
NoMethodError (undefined method `read_attribute_for_serialization' for
#<Hash:0x007f90cbed0ba8>):...
I have also tried including ActiveModel::Serialization in the custom serializer which then I get another error as below:
NoMethodError (undefined method `id' for #<GroupedItemSerializer:0x007fa47012ad38>):...
adding attributes :id doesn't resolve the issue though.
Here's my setup:
Initializer:
ActiveModel::Serializer.config.adapter = :json_api
Model Serializer:
class ItemSerializer < ActiveModel::Serializer
attributes :id, :code, :name, :item_type, ....
end
Custom Serializer:
class GroupedItemSerializer < ActiveModel::Serializer
def serializable_object(options = {})
#object.map do |group_key, items|
[group_key, serialized_items(items)]
end.to_h
end
private
def serialized_items(items)
items.map do |item|
ItemSerializer.new(item, root: false)
end
end
end
Controller:
#items = Item.all.group_by(&:item_type)
# using each_serializer also doesn't help as it only uses the
# GroupedItemserializer and not applying the ItemSerializer!
render json: #items, serializer: GroupedItemSerializer
Not sure if I'm missing something in the documentation, but I've tried all the possible ways to achieve this. Any help would be appreciated.

Rails 4 - ActionMailer helper undefined method `session'

I'm new to Rails and I'm having a hard time understanding why my helper module doesn't work when called from the ActionMailer. I'm calling the same method from a different partial and it works fine. The problem is not so much the method but my session variable (session[:geo]) - it says "undefined method `session'".
here is my code any suggestion is much appreciated
products_helper.rb
def isUserLocal?
session[:geo] #true or false
end
def itemTotalPrice(item)
if self.isUserLocal?
item.line_item_us_total_price
else
item.line_item_w_total_price
end
end
order-notifier - ActionMailer
class OrderNotifier < ActionMailer::Base
helper :Products #helpers are not available in ActionMailers by default
received.html.erb
<%= render #order.line_items -%>
_line_items.html.erb
number_to_currency(itemTotalPrice(line_item))

Rails 3 ActiveModel::Serializers seem to need lots of support methods

I'm returning to RoR after not using it for a few years and I'm trying to use ActiveModel to serialise a plain object to XML.
I'm doing the following, as per the comments in activemodel/lib/activemodel/serialization.rb:
class XmlError
include ActiveModel::Serializers::Xml
attr_accessor :code
attr_accessor :description
def attributes
#attributes ||= {'code' => 'nil', 'description' => 'nil'}
end
def initialize(error_code)
#code = error_code
#description = "blah"
self
end
end
I use this in a controller as:
render :xml => XmlError.new("invalid_login")
and I get the following stacktrace:
NoMethodError (undefined method `model_name' for XmlError:Class):
app/controllers/users_controller.rb:19:in `login'
app/controllers/users_controller.rb:5:in `login'
If create a model_name class method, I then get the following stacktrace:
NoMethodError (undefined method `element' for "XmlError":String):
app/controllers/users_controller.rb:19:in `login'
app/controllers/users_controller.rb:5:in `login'
It feels like I'm chasing my tail here. Have I just missed something simple in my class? I followed the example closely.
extend ActiveModel::Naming
is what you are looking for.
http://rdoc.info/github/lifo/docrails/master/ActiveModel/Naming
Why not sub-class ActiveModel::Base?

Resources