I am trying to make an app with Rails 4.
I am using pundit with devise.
I am trying to write an Address Policy in Pundit.
I have three relevant models, being user.rb, profile.rb and address.rb.
The associations are:
user.rb
has_one :profile
profile.rb
belongs_to :user
has_many :addresses, as: :addressable
address.rb
belongs_to :addressable, :polymorphic => true
My address policy is:
class AddressPolicy < ApplicationPolicy
def create?
user.present? && user == address.profile.user
end
def update?
user.present? && user == address.profile.user
end
def destroy?
user.admin?
end
private
def address
record
end
end
Im having trouble how to figure out the way to write this policy. Address is polymorphic. Profile can have many addresses and a profile belongs to a user. So, for the policy I want the user who owns the profile to create and update addresses. I'm struggling because I can't figure out how to put profile into the chain of associations to link between user and address.
The current error method with this policy starts with the create? function:
def create?
user.present? && user == address.profile.user
end
The message is:
undefined method `profile' for #<Address:0x007fbad7ac0cf8>
My address policy inherits from my application policy, which initialises user and record:
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
@user = user
@record = record
end
Can anyone see how to do this?
You could check if the user's addresses include the address:
user && user.profile.addresses.exists?(address.id)