【问题标题】:RoR3 HABTM Checkboxes Not SavingRoR3 HABTM 复选框未保存
【发布时间】:2011-11-13 21:35:46
【问题描述】:

在控制台中,我的查询运行良好:

u = Radcheck.get(23)
g = Group.get(16) 
@relationship = u.radgroups << g

然后保存写入数据库。

当我在 Rails 视图中尝试这样做时,它不会保存。

<%= check_box_tag "radcheck[groupnames][]", group.id, @radcheck.radgroups.include?(group) %> 

我正在使用 datamapper,并有这样的 radcheck 模型设置:

has n, :radusergroup, :child_key => [:username], :parent_key => [:username]
has n, :radgroups, :through => :radusergroup, :model => 'Group'

我的 radcheck 表包含用户名和组名列

有什么建议吗?

-- 更新--

为了进一步回答下面的问题,我在 radusergroup 表(我的联接表)中添加了一个 id。目前看起来像这样:

+-------------+---------------------------+----------+----+
| username    | groupname                 | priority | id |
+-------------+---------------------------+----------+----+
| hcTTm       | 3600                      |        1 |  1 |
| FpKS4       | 3600                      |        1 |  2 |
| jenny       | Disabled-Users            |        1 |  3 |
| silver      | silver                    |        1 |  4 |
| shushQb     | 30-minutes                |        0 |  5 |
| jenny       | silver                    |        1 |  6 |
+-------------+---------------------------+----------+----+

这让我现在分心

我的模型中有完全正确的信息,只能假设问题出在存档?

【问题讨论】:

  • 建议您通过删除一些从未得到答案的旧问题(不是 11 月的问题)来提高您的接受率(问题的第 2 页)。
  • 谢谢,我会这样做的。不太确定为什么这会影响这个问题?

标签: ruby-on-rails ruby ruby-on-rails-3 datamapper


【解决方案1】:

改为使用 groupname_ids

<%= check_box_tag "radcheck[groupname_ids][]", group.id, @radcheck.radgroups.include?(group) %>

此外,最好停止使用 HABTM。使用 has_many :through

EXAMPLE USER 通过 user_roles 拥有多个角色

class User 
  has_many :user_roles
  has_many :roles, :through => :user_roles
end
class UserRole
  belongs_to :role
  belongs_to :user
end
class Role
  has_many :user_roles
  has_many :users, :through => :user_roles
end

并向连接表添加一个 ID。

【讨论】:

  • 感谢您的回复,遗憾的是这也不起作用。在我的模型中,我使用了很多通过 - 也许这就是问题所在。 a has many through rel 的语法是什么?
  • 例如...对于用户类... has_many :user_roles THEN has_many :roles, :through => :user_roles |||但是您需要连接表中的 id 字段。您还需要一个带有 belongs_to :role AND belongs_to :user 的类 UserRole
  • 尽管我尽了最大的努力,它仍然无法正常工作。我现在假设这是一个数据映射器问题,而不是代码问题。我什至看不到日志中发生的插入。有更新的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-08
  • 2010-12-18
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-16
相关资源
最近更新 更多