Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

undefined method `#{parent_name}=' for singleton associations #795

Open
heaven opened this issue Jul 4, 2022 · 0 comments
Open

undefined method `#{parent_name}=' for singleton associations #795

heaven opened this issue Jul 4, 2022 · 0 comments

Comments

@heaven
Copy link

heaven commented Jul 4, 2022

Steps to reproduce

The code below produces this error when assigning the parent to the new resource using the :through parameter that points to a method in the controller.

class Member < ApplicationRecord
  has_one :subscription, class_name: "Billing::Subscription", inverse_of: :member
end

class Billing::Subscription < ApplicationRecord
  belongs_to :member, inverse_of: :subscription
end

class API::V1::Billing::SubscriptionsController < API::APIController
  load_and_authorize_resource class: "Billing::Subscription", through: :current_member, singleton: true

  def create
    @subscription.save!
    respond_with(@subscription, location: api_v1_billing_subscription_url)
  end
end

Expected behavior

@subscription.member should have been assigned, instead of @subscription.current_member.

There are a few workarounds to this. First, there's the inverse_of parameter on associations, so it's possible to find the reflection and get the proper name. Additionally, when inverse_of is present, you probably don't have to assign the parent manually but rather use build_#{resource_name}.

Another option is to add a new inverse_of option to load_and_authorize_resource method, where we can explicitly specify the parent name.

Actual behavior

undefined method `current_member=' for #<Billing::Subscription id: nil, member_id: nil, price_id: 1, status: "created", ...

System configuration

Rails version: 7.0.3
Ruby version: ruby 3.1.1p18 (2022-02-18 revision 53f5fc4236) [x86_64-darwin20]
CanCanCan version: 3.3.0, 3.4.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant