嵌套形式 &哈布特姆
我正在尝试保存到 habtm 关系中的联接表,但遇到问题。
从我看来,我传入的组 ID 为:
<%= link_to "Create New User", new_user_url(:group => 1) %>
# User model (user.rb)
class User < ActiveRecord::Base
has_and_belongs_to_many :user_groups
accepts_nested_attributes_for :user_groups
end
# UserGroups model (user_groups.rb)
class UserGroup < ActiveRecord::Base
has_and_belongs_to_many :users
end
# users_controller.rb
def new
@user = User.new(:user_group_ids => params[:group])
end
在新的用户视图中,我可以访问 User.user_groups 对象,但是当我提交表单时,它不仅不会保存到我的联接表(user_groups_users)中,而且该对象不再存在。所有其他对象和除了用户组之外,我的用户对象的属性是持久的。
我刚刚开始学习 Rails,所以也许我在概念上遗漏了一些东西,但我一直在努力解决这个问题。
I am trying to save to a join table in a habtm relationship, but I am having problems.
From my view, I pass in a group id with:
<%= link_to "Create New User", new_user_url(:group => 1) %>
# User model (user.rb)
class User < ActiveRecord::Base
has_and_belongs_to_many :user_groups
accepts_nested_attributes_for :user_groups
end
# UserGroups model (user_groups.rb)
class UserGroup < ActiveRecord::Base
has_and_belongs_to_many :users
end
# users_controller.rb
def new
@user = User.new(:user_group_ids => params[:group])
end
in the new user view, i have access to the User.user_groups object, however when i submit the form, not only does it not save into my join table (user_groups_users), but the object is no longer there. all the other objects & attributes of my User object are persistent except for the user group.
i just started learning rails, so maybe i am missing something conceptually here, but i have been really struggling with this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否考虑过将用户添加到控制器中的组中,而不是使用accepts_nested_attributes_for?这样你就不需要来回传递 user_group_id 。
在 users_controller.rb 中:
这样您还可以阻止人们修改表单并将自己添加到他们想要的任何组中。
Instead of using accepts_nested_attributes_for, have you considered just adding the user to the group in your controller? That way you don't need to pass user_group_id back and forth.
In users_controller.rb:
This way you'll also stop people from doctoring the form and adding themselves to whichever group they wanted.
users_controller.rb 中的创建方法是什么样的?
例如,如果您在视图中使用 fields_for 构造:
您应该能够将 params[:user] (或其他任何内容)传递给 User.new() ,它将处理嵌套属性。
What does your create method look like in users_controller.rb?
If you're using the fields_for construct in your view, for example:
You should be able to just pass the params[:user] (or whatever it is) to User.new() and it will handle the nested attributes.
扩展 @jimworm 的答案:
这样,您就可以从 params 哈希中提取哈希并仅收集 id。现在您可以单独保存用户,例如:
并在一行中单独添加/删除他的组 ID:
Expanding on @jimworm 's answer:
That way, you've yanked the hash out of the params hash and collected the ids only. Now you can save the user separately, like:
and add/remove his group ids separately in one line: