对Rails不熟悉所以对我很轻松: - )
我有两个模型:用户和角色:
class User < ActiveRecord::Base
has_many :roles
accepts_nested_attributes_for :roles
validates_presence_of :role_id
end
class Role < ActiveRecord::Base
belongs_to :user
end
用户拥有外键的role_id。
我要做的就是能够在用户/新表单中为用户选择一个角色。我知道这很容易,但我似乎无法弄明白......今天我已经读了好几个小时试图解决这个问题。下拉选择列表出现在视图中,但它始终未通过验证(如显示,但从未实际关联用户选择的User.role_id)
以下是我在表单中的部分内容以显示下拉列表:
<%= f.collection_select :role_id, Role.all, :id, :name %>
有人能指出我正确的方向吗?也许我必须使用某种嵌套形式,但我尝试的任何东西似乎都没有用,这就是我现在所拥有的。我是否必须在控制器中执行某些操作?
答案 0 :(得分:1)
如果用户有很多角色,那么您的用户模型必须没有字段:user_id
,我认为,我希望,用户拥有和属于许多角色。那你需要第三个模型:
class User < ActiveRecord::Base
has_many :user_roles
has_many :roles, through: :user_roles
end
class Role < ActiveRecord::Base
has_many :user_roles
has_many :users, through: :user_roles
end
class UserRole < ActiveRecord::Base
belongs_to :user
belongs_to :role
validates_presence_of :role_id, :user_id
end
在您的用户表单中,您可以使用它来更新关系(看起来::role_ids
复数形式)
<%= f.collection_select :role_ids, Role.all, :id, :name, {}, {multiple: true} %>
验证现在在UserRole模型中。
编辑:如果您使用的是Rails 4.x,则需要允许params获取role_ids的集合。
params.require(:user).permit(:user_field1, :user_field2, ... , role_ids: [])