So I recently created an HABTM relationship between two models (project & user).
Before, I had a user_id column in my project table – that would act like a foreign key. Now there is an entire table that does that.
But how do I reference projects that have a specific user_id & project_id ?
For instance, I used to have a section of my view that looked like this:
<div class="field">
<%= f.label :project_id %><br />
<%= collection_select(:stage, :project_id, Project.where(:user_id => current_user), :id, :name) %>
<br />
</div>
But how do I now pull the same info from the db, with no model for the HABTM table? The new table is called ‘projects_users’.
My projects model looks like this:
# == Schema Information
# Schema version: 20101125223049
#
# Table name: projects
#
# id :integer not null, primary key
# name :string(255)
# description :string(255)
# notified :boolean
# created_at :datetime
# updated_at :datetime
#
class Project < ActiveRecord::Base
has_and_belongs_to_many :users
has_many :stages, :dependent => :destroy
has_many :uploads
has_many :comments
#before_validation { |project| project.user = Authorization.current_user unless project.user }
end
My User Model looks like this:
# == Schema Information
# Schema version: 20101124095341
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255) default(""), not null
# encrypted_password :string(128) default(""), not null
# password_salt :string(255) default(""), not null
# reset_password_token :string(255)
# remember_token :string(255)
# remember_created_at :datetime
# sign_in_count :integer default(0)
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# created_at :datetime
# updated_at :datetime
# username :string(255)
# role :string(255)
#
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, and :lockable
devise :database_authenticatable, :registerable, :timeoutable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
has_and_belongs_to_many :projects
has_many :stages
has_many :uploads
has_many :comments
has_many :assignments
has_many :roles, :through => :assignments
def role_symbols
roles.map do |role|
role.name.underscore.to_sym
end
end
end
As an aside…how do I edit that table from the rails console – without a model?
Thanks.
I’m not sure I fully understand your question, but
Project.where(:user_id => current_user)should becomecurrent_user.projectsAnd to add user with id 1 to project with id 3 you’d do
Is this what you’ve been trying to do ?