Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 将对象添加到has\ U MUN THRON关系时设置联接表属性_Ruby On Rails_Ruby On Rails 3_Activerecord - Fatal编程技术网

Ruby on rails 将对象添加到has\ U MUN THRON关系时设置联接表属性

Ruby on rails 将对象添加到has\ U MUN THRON关系时设置联接表属性,ruby-on-rails,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby On Rails 3,Activerecord,在我的Ruby on Rails 3.2.3应用程序中,我有两个模型通过has_many through关系通过第三个模型连接: class Organization < ActiveRecord::Base attr_accessible :description, :name has_many :roles, dependent: :destroy has_many :members, through: :roles, source: :user end class Ro

在我的Ruby on Rails 3.2.3应用程序中,我有两个模型通过has_many through关系通过第三个模型连接:

class Organization < ActiveRecord::Base
  attr_accessible :description, :name
  has_many :roles, dependent: :destroy
  has_many :members, through: :roles, source: :user
end

class Role < ActiveRecord::Base
  attr_accessible :title
  belongs_to :organization
  belongs_to :user
end

class User < ActiveRecord::Base
  attr_accessible :email, :fullname
  has_many :roles, dependent: :destroy
  has_many :organizations, through: :roles
end

我知道我可以直接创建一个
角色
实例。但是,在使用
时,在联接表上指定属性的更优雅的方法是什么?我认为您正在尝试使用不属于其中的信息更新角色表。在您的情况下,角色名称应包含在组织或用户中,而不是您的加入表中。无论是包含在父模型中,还是更好地创建另一个联接表,以便可以将角色与用户连接起来

class role_users < ActiveRecord::Base
  attr_accessible :user_id, role_id
  belongs_to :user
  belongs_to :role
end

class Roles < ActiveRecord::Base
  attr_accessible :title, :foo, :bar
  has_many :role_users
  has_many :users, :through => :role_users
end    

class Users < ActiveRecord::Base
  attr_accessible :other, :foo, :bar
  has_many :role_users
  has_many :roles, :through => :role_users
end
类角色用户:角色\u用户
结束
类用户:角色\u用户
结束

然后像我们一样自己设置这些角色,并添加一个复选框或下拉列表,以便用户可以选择。或者让用户自己输入信息。

为什么不在模型中使用validates presence of而不是在数据库中输入not null?我在
角色中有
validates\u presence of:title
。它在模型级别和数据库级别都强制执行。然而,Rails仍然会抛出MySQL错误,而不是一些验证错误。你能从数据库中删除验证并看看会发生什么吗?另外,如果角色不同或数量固定,你会有很多人吗?例如,admin、accounts、staff?在本例中,
title
可以是任何内容(“副总裁”、“司库”等等)。我非常相信数据库的效率,包括将字段定义为
notnull
和具有外键,因此我不想从数据库中删除该声明。中的示例显示了一个“联接表”,其中包含两个外键以外的其他字段。在设计我的模式时,我从那里得到了灵感。有很多方法可以用栏杆给猫剥皮。这只是我对你提出的问题的建议。
class role_users < ActiveRecord::Base
  attr_accessible :user_id, role_id
  belongs_to :user
  belongs_to :role
end

class Roles < ActiveRecord::Base
  attr_accessible :title, :foo, :bar
  has_many :role_users
  has_many :users, :through => :role_users
end    

class Users < ActiveRecord::Base
  attr_accessible :other, :foo, :bar
  has_many :role_users
  has_many :roles, :through => :role_users
end