I am working on a project in rails 4 where a user can have multiple projects and many people are associated with a single project. ie. Projects and users share a many to many relationship.
I created a new table by using this migration code -
class CreateProjectsUsersJoin < ActiveRecord::Migration
def change
create_table :projects_users_joins, :id => false do |t|
t.integer :user_id
t.integer :project_id
end
add_index :projects_users_joins, ["user_id","project_id"]
end
end
and added associations in the following way -
class Project < ActiveRecord::Base
validates :name , :presence => true
validates :description, :presence => true
#associations
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
include CarrierWave::MiniMagick
#removes the white spaces before validating the data
before_validation :strip_whitespace, :only => [:name,:email]
#data validations
validates :email, :presence =>true, :uniqueness => {case_sensitive: false}, :format => { :with=> /([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/, :message => "please enter a valid e-mail" }
validates :name, :presence=>true
validates :password ,:presence =>true, :confirmation=> true #, :length =>{ :minimum=>6, :maximum=>30}, :format=>{:with=>/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,30}/}
#for the image
mount_uploader :image, ImageUploader
#for the password
has_secure_password
#associations
has_many :issues
has_many :comments
has_and_belongs_to_many :projects
end
#squishes the data(removes heading and trailing white spaces and replaces multiple space by songle)
def strip_whitespace
self.email = self.email.squish
self.name = self.name.squish
end
when I run the following commands on rails console I get a no method error - Please help
pro = Project.find(1) (works)
me = User.find(27) (works)
pro.users << me (throws a no method defined error)
Please help
Aucun commentaire:
Enregistrer un commentaire