[Rails] #has_and_belongs_to_many problem

D

Dmitry V. Sabanin

Hi,

I'm playing with Rails and I must say that it's really great framework. Web
development was never been so easy and pleasure. However, I'm having a lot of
small problems in understanding the New Way(TM) of creating stuff for web.

I have a problem when I try to extend ACL example that's listed on wiki:
http://activerecord.rubyonrails.org/show/AccessControlListExample
There's model Role and Permission, Role#has_and_belongs_to_many permissions,
and everything works fine. But, when I remove a Permission that belongs to
some Role, I still see reference to it in `permissions_roles` table. I've
tried following code to delete all permissions from Role's that use them, but
it doesn't work also, links to non-existant Permissions are still in
`permissions_roles` table:

class Permission < ActiveRecord::Base
has_and_belongs_to_many :roles

def before_destroy
Role.find_all.each do |role|
role.permissions(true).each do |perm|
# I'm comparing id's here because i'm not sure if
# ActiveRecord handles #== right
if perm.id == read_attribute("id")
role.remove_permissions(perm.id)
role.save
end
end
end
end

end

P.S. Maybe that's a problem with me being using MySQL, which has no support
for foreign keys in stable version?
 
D

David Heinemeier Hansson

Try this instead:

class Permission < ActiveRecord::Base
has_and_belongs_to_many :roles

protected
def before_destroy
connection.delete(
"DELETE * FROM permissions_roles WHERE permission_id = #{id}"
)
end
end

Some times a little SQL is just what you need. Active Record doesn't
look down upon you for doing that. Unlike many other frameworks.

I'll get a :dependent => true option in at some point that'll do this
automatically, though.

Oh, and thanks for the praise! I'm glad you're having fun and are being
productive.
--
David Heinemeier Hansson,
http://www.rubyonrails.org/ -- Web-application framework for Ruby
http://www.instiki.org/ -- A No-Step-Three Wiki in Ruby
http://www.basecamphq.com/ -- Web-based Project Management
http://www.loudthinking.com/ -- Broadcasting Brain
http://www.nextangle.com/ -- Development & Consulting Services
 
A

Andreas Schwarz

Dmitry said:
P.S. Maybe that's a problem with me being using MySQL, which has no support
for foreign keys in stable version?

Foreign keys are supported in 4.x, but only with InnoDB tables.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,602
Members
45,185
Latest member
GluceaReviews

Latest Threads

Top