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

Creating resource failes when association is polymorphic and singleton. #830

Open
ccfz opened this issue Aug 15, 2023 · 0 comments
Open

Comments

@ccfz
Copy link

ccfz commented Aug 15, 2023

Steps to reproduce

Given I have the following association:

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true, optional: true, inverse_of: :comments
end

class Post < ApplicationRecord
  has_one :comment, as: :commentable, inverse_of: :commentable
end

class Photo < ApplicationRecord
  has_many :comments, as: :commentable, inverse_of: :commentable
end

and the following controller:

  class CommentsController < ApplicationController

    load_and_authorize_resource :post
    load_and_authorize_resource through: :post, singleton: true

I ran into a problem when building the resource and assigning the attributes here.

def assign_attributes(resource)
  resource.send("#{parent_name}=", parent_resource) if @options[:singleton] && parent_resource
  initial_attributes.each do |attr_name, value|
    resource.send("#{attr_name}=", value)
  end
  resource
end

The line: resource.send("#{parent_name}=", parent_resource) if @options[:singleton] && parent_resource fails because the parent_resource in a polymorphic association is not post but commentable=. Therefore, we get the error:

 NoMethodError:
       undefined method `post=' for #<Comment

Expected behavior

I can instantiate a polymorphic association correctly.

Actual behavior

I get an undefined method error.

System configuration

Rails version:
7.0.7
Ruby version:
3.2.2.
CanCanCan version
3.5

@ccfz ccfz changed the title Creating resource failes when association is polymorphic and singlton. Creating resource failes when association is polymorphic and singleton. Aug 15, 2023
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