【问题标题】:Mass assignment with update_attributes does not update collection_singular_ids使用 update_attributes 进行批量分配不会更新 collection_singular_ids
【发布时间】:2012-07-04 12:03:25
【问题描述】:

我有一个简单的 User 模型,它使用连接表 (has_and_belongs_to_many) 与许多 Town 对象相关联。现在我想通过分配以逗号分隔的城镇 ID 列表(直接来自作为 HTTP POST 参数发送的表单)来更新属于特定用户的城镇。

使用以下控制器代码保存用户对象:

@current_object.update_attributes(params[:user])

params[:user] 包括 town_ids,例如设置为 1,4,6

不幸的是,这根本不会更新用户与城镇的关联。但是,如果我手动操作,效果会非常好:

User.find(:first).town_ids = "1,4,6" # this saves automatically

难道只是无法批量分配这些collection_singular_ids 字段吗?

我的用户模型包含以下内容:

has_and_belongs_to_many :towns

# necessary for mass-assignment, otherwise it results in an exception:
attr_accessible :town_ids

非常感谢任何帮助。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord mass-assignment


    【解决方案1】:

    你必须将town_ids 作为一个数组传递:

    User.find(:first).update_attributes(:town_ids=>[1,4,6])
    

    如果您将 id 作为字符串传递,Rails 将尝试将字符串转换为整数:

    "1,4,6".to_i # => 1
    

    【讨论】:

      猜你喜欢
      • 2012-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-04
      • 2012-09-21
      • 2016-05-02
      • 1970-01-01
      相关资源
      最近更新 更多