我正在使用rails 4中的项目,其中用户可以拥有多个项目,并且许多人与单个项目相关联。即。项目和用户分享了多对多的关系。
我使用此迁移代码创建了一个新表 -
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
并以下列方式添加关联 -
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
当我在rails控制台上运行以下命令时,我得到一个no方法错误 - 请帮忙
pro = Project.find(1) (works)
me = User.find(27) (works)
pro.users << me (throws a no method defined error)
请帮忙
答案 0 :(得分:0)
你的表名错了。 As the docs say默认连接表名称应该只是用下划线连接的词法顺序中的两个类的复数名称。在这种情况下projects_users
。
如果您需要projects_users_joins
,那么您可以在:join_table
次调用中提供habtm
选项,或者(我的推荐)执行该rake db:migrate:down
次迁移,然后删除"_joins"
并再次迁移以生成默认表名。