has_one and has_many association throw[ wrong number of arguments (given 1, expected 0)] when passed with proc shortcut - ruby-on-rails-5.2

I had rails 4.2 and ruby 2.3.5 and I'm upgrading it to rails 5.2 with ruby 2.6.1.
With older rails version(4.2) my UserAuthenticatedSerializer is working fine and was giving a proper response.
After upgrading to rails 5.2 my Serializer started throwing an argument error.
I debugged it and it's throwing from relationship.rb file method name fetch_id and fetch_associated_object Here in both methods, object_block.call(record, params) throwing an argument error.
If I remove the second parameter from the params it works fine. Passing these two arguments causes an error.
This same association work with rails 4.2 but it's not working in rails 5.2.
Here is my code snap :
response = UserAuthenticatedSerializer.new(#user, { params: { domain: current_domain } }).to_json
error = ArgumentError (wrong number of arguments (given 1, expected 0))
user_authenticated_serializer.rb ===>
class UserAuthenticatedSerializer
include FastJsonapi::ObjectSerializer
has_one :user_profile, serializer: UserProfileSerializer, &:user_profile
has_many :user_topic_label_order, &:user_topic_label_order
end
user.rb ====>
Relationship in user model:
has_one :user_profile, dependent: :destroy
has_many :user_topic_label_order, dependent: :destroy
Rails version : 5.2.2
Ruby version : ruby 2.6.1
fast_jsonapi gem version : fast_jsonapi (1.5)
active_model_serializers (~> 0.10.9)

The error comes from your serializer, namely from passing an extra argument to has_one. Try this instead:
class UserAuthenticatedSerializer
include FastJsonapi::ObjectSerializer
attributes :name, :address
has_one :user_profile #, &:user_profile
end
You don't need to pass in anything extra.

Related

Rails 6: How to conditionally validate an association for presence?

I have the following 2 models:
class Offer < ApplicationRecord
has_many :bookings
end
class Booking < ApplicationRecord
belongs_to :offer
end
When I attempt to save a Booking object without an offer_id, Rails throws a validation error "Offer is required".
But I don't actively validate for presence of associated objects (I intended to add a conditional validation for this association later).
Does that mean that Rails 6 validates the presence of all associations by default? And if yes, how can I make such a validation a conditional one?
Starting from Rails 5, belongs_to adds presence validation by default.
You can disable this behavior in application.rb with:
config.active_record.belongs_to_required_by_default = false
Or if you want it to be optional only in this belongs_to you can pass optional option to belongs_to:
belongs_to :offer, optional: true

"ArgumentError: Unknown key: :conditions" for has_many association when upgrading from Rails 3 to Rails 4

I am migrating from Rails 3 to Rails 4 and the following associations from one of my models is causing an error:
has_many :unblocked_items, class_name: 'IncidentItem',
conditions: [
'incident_items.item_type_id in (?) \
AND (incident_blocking_file_id IS NULL OR incident_blocking_files.way = ? \
)',
IncidentItemType.blockable,
BlockingWay.unblock
],
include: :incident_blocking_file
has_many :blocked_items, class_name: 'IncidentItem',
conditions: [
'incident_items.item_type_id in (?) \
AND (incident_blocking_file_id IS NOT NULL \
AND (incident_blocking_files.way <> ? OR incident_blocking_files.way IS NULL) \
)',
IncidentItemType.blockable,
BlockingWay.unblock
],
include: :incident_blocking_file
I get the following error:
ArgumentError: Unknown key: :conditions. Valid keys are: :class_name, :anonymous_class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type (ArgumentError)
What causes this error? How can I migrate this model and its associations from Rails 3 to Rails 4?
from: https://edgeguides.rubyonrails.org/association_basics.html#scopes-for-has-many
4.3.3 Scopes for has_many
There may be times when you wish to customize the query used by has_many. Such customizations can be achieved via a scope block. For example:
class Author < ApplicationRecord
has_many :books, -> { where processed: true }
end

Rails 4: what's wrong with this scope?

In Rails 3.2 this worked fine:
class Component < ActiveRecord::Base
has_and_belongs_to_many :brands
...
scope :branded, ->(b) { includes(:brands).where('brands.id in (?)', b.id) }
Other end of the relationship:
class Brand < ActiveRecord::Base
has_and_belongs_to_many :components
But I'm upgrading to Rails 4 and it breaks with this message:
Unknown column 'components.brand_ids' in 'where clause'
What's the problem here?
UPDATE
I haven't made the switch to strong parameters yet, and I'm using the protected_attributes gem. Could that be the cause of all this?
Not sure what the branded scope is trying to do, but with the assumption it is to find components that are have a brand X, Component.branded(Brand.find(X))
Maybe try this:
scope :branded, ->(b) { joins(:brands).where(Brand.arel_table[:id].eq b.id)}

Rails 3 Collection `sum` fails with TypeError

In a sample Rails 3.2.8 app (on Ruby 1.9.3) there is the following simple setup:
class Account < ActiveRecord::Base
has_many :line_items
def subtotal
line_items.sum(&:price)
end
end
class Line_Item < ActiveRecord::Base
belongs_to :product
def price
product.price * time
end
end
account = Account.new
account.line_items.build do |item|
item.years = 4
item.product = Product.last
end
account.subtotal
#=> TypeError: nil can't be coerced into BigDecimal
As above the subtotal method fails with a conversion error. In subtotal I checked the type returned by line_items.class and got Array. If I update the definition of subtotal to either of the following, the method works:
line_items.to_a.sum(&:price)
#=> #<BigDecimal:7ff4d34ca7c8,'0.0',9(36)>
line_items.map(&:price).sum
#=> #<BigDecimal:7ff4d3373b40,'0.0',9(36)>
Why does the initial definition of line_items.sum(&:price) fail?
This appears to be a bug in Rails (at least in 3.2.8).
In Rails 3.2.8, the has_many association is dynamically defining collection.sum.
Though this isn't reflected in A Guide to Active Record Associations
or ActiveRecord::Associations::ClassMethods API docs; it is briefly listed in the API under the "Collection associations (one-to-many / many-to-many)"
chart, but not referenced again.
According to the code, it will always try to hit the database using a SQL sum.
However, in this particular instance, the model isn't saved. So there's nothing
in the database.
So to clear that up a little:
account.line_items.sum(&:price) # Uses Collection#sum, goes to database
account.line_items.map.sum(&:price) # Uses Enumerable#map then Enumerable#sum
This has been logged under issue #7928; which appears related to issue #5215: "finders and scopes on has_many association on new object incorrectly query db for null foreign keys".

Rails 3 relationship definition problem?

I'm new to Rails 3, i'm creating a web app that use active admin, i get a problem with him, and asked for help inside github plugin, someone told me maybe a relationship definitions.
I really dont know what is that, i have nested elements and in active admin i want to make nested element independent.
but now, im totally lost. what i missed? thanks.
here is my model definition
class Company < ActiveRecord::Base
before_save :getsubdomain
has_attached_file :logo, :styles => { :thumb => '150x150>', :medium => '250x250>', :normal => '350x350>'}
has_many :buildings
accepts_nested_attributes_for :buildings
end
Building model
class Building < ActiveRecord::Base
belongs_to :companies
end
in my db, i have colum company_id in buildings table.
Here the error message i get..
NameError in Admin/buildings#index
Showing /Library/Ruby/Gems/1.8/bundler/gems/active_admin-c3a1ffa98072/app/views/active_admin/resource/index.html.arb where line #1 raised:
uninitialized constant Building::Companies
Rails.root: /Users/username/Sites/myapps
Request
Parameters:
{"order"=>"id_desc"}
Response
Headers:
None
thanks for your help
belongs_to expects a singular name. Try
belongs_to :company

Resources