views:

69

answers:

1

I'm a bit of a newb to ruby and I am having a heck of a problem with the has_many :through associations. My system is currently set up with Authlogic and Declarative_auth. At the moment when I file a user it creates everything correctly except it doesnt insert the role_id in the users table even though it shows its being passed on submit. It also doesn't save the id's in the assignment table. First off I guess the question is, is role_id even necessary in the users table? Secondly do the user_id and role_id fields in the assignment table need to be declared as a foreign_key or does rails automatically handle this? I appreciate any help on this.

class User < ActiveRecord::Base
  acts_as_authentic
  has_many :assignments
  has_many :roles, :through => :assignments

  def role_symbols
    roles.map do |role|
      role.name.underscore.to_sym
    end
  end
end

class Role < ActiveRecord::Base
  has_many :assignments
  has_many :users, :through => :assignments
end

class Assignment < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
end
A: 

is role_id even necessary in the users table?

No, the role_id column should only be in the assignments table. In this case the users table won't be updated at all, just assignments. Likely a new Assignment should be created with the the given role_id and user_id.

do the user_id and role_id fields in the assignment table need to be declared as a foreign_key or does rails automatically handle this?

DB-level constraints are not required by Rails. The only thing needed for Rails to work with the associations are the association declarations themselves and the presence of the corresponding id columns in the appropriate tables.

This Railscast is a good intro to has_many :through.

Dave Sims
Also this http://railscasts.com/episodes/188-declarative-authorization
mark