【问题标题】:Serializing to array shows empty brackets and formats incorrectly in Rails序列化为数组在 Rails 中显示空括号和格式不正确
【发布时间】:2013-08-06 10:08:29
【问题描述】:

我的组织模型中有一个部门字段,我想将部门列表存储为一个数组。我的模型中有这个:

class Org < ActiveRecord::Base
   serialize :department, Array
   attr_accessible :name, :department
   before_validation :update_department
   validates :name, presence: true
   def update_department
    if department_changed? and department.is_a?(String)
     self.department = self.department.split(',').collect(&:strip) 
    end
  end
end

和视图:

<%= f.text_area :department, :cols => "10", :rows => "10" %>

现在每当我尝试注册时,部门字段都会显示 [],而当我尝试更新时,部门字段已经是 ["[department1", "department2]"]。

我希望在注册时删除 [],并在更新时显示部门 1、部门 2。数组也保存不正确,应该是["department1", "department2"]。

请帮忙。

【问题讨论】:

    标签: ruby-on-rails arrays serialization


    【解决方案1】:

    你应该用逗号加入数组

    object.join(',')
    

    在你的例子中:

    <%= f.text_area :department,value: @org.department.join(','), :cols => "10", :rows => "10" %>
    

    【讨论】:

      猜你喜欢
      • 2014-05-27
      • 2019-06-26
      • 2017-09-22
      • 1970-01-01
      • 2020-05-05
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多