【问题标题】:Error: ActiveRecord automatically escape input array from check_box_tag (Rails 3)错误:ActiveRecord 自动从 check_box_tag 中转义输入数组(Rails 3)
【发布时间】:2011-09-04 15:37:05
【问题描述】:

我有 PrivateMessage 模型,其 :to 字段可能包含多个收件人 ID。

create_table :private_messages do |t|
  t.integer :author_id
  t.string :subject
  t.text :body
  t.text :to
  t.timestamps

我使用 check_box_tag 让发件人选择他想要发送到的收件人:

<% for friend in User.find(:all) %>
  <%=raw check_box_tag "private_message[to][]", friend.id, @private_message.to.include?(friend.id)%> 
  <%= friend.username %><br />
<% end %>

当用户选择多个收件人时,参数传递OK:

tarted POST "/sent" for 127.0.0.1 at 2011-09-04 11:02:26 -0400
  Processing by SentController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"XXX", "private_message"=>{"to"=>["8", "9", "10"], "subject"=>"test"}, "commit"=>"Send"}

但是,当该行插入到我的表中时,它会自动转义如下:

  SQL (0.4ms)  INSERT INTO "private_messages" ("author_id", "body", "created_at", "subject", "to", "updated_at") VALUES (10, '2011-09-04 15:20:47.009706', 'test', '--- 
- "8"
- "9"
- "10"
', '2011-09-04 15:20:47.009706')

当我在控制台上查看记录时:

ruby-1.9.2-p180 :010 > PrivateMessage.last.to
 => "--- \n- \"8\"\n- \"9\"\n- \"10\"\n" 

我的问题是:我应该如何将 :to 记录为“7”、“8”、“10”?

非常感谢您的帮助!

P/S:我正在学习这里的教程:http://www.novawave.net/public/rails_messaging_tutorial.html

【问题讨论】:

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


    【解决方案1】:

    您不应使用单个字段来保存对多个收件人的引用。相反,您的模型应如下所示:

    class PrivateMessage
      has_and_belongs_to_many :recipients
    end
    
    class Recipient
      has_and_belongs_to_many :private_messages
    end
    

    这样,您的 PrivateMessage 和 Recipient 模型将通过第三个表关联(您不必为此烦恼,Rails 会为您完成所有背景工作),您将获得类似的 getter 和 setter

    @private_message.recipients = Recipient.find_by_id(params[:to])
    

    @private_message.recipients_singular_ids = params[:to].to_a
    

    它并没有完全回答你的问题,但我认为你绝对应该这样看。我也热烈推荐你阅读关于关联的 RoR/AR 指南:http://guides.rubyonrails.org/association_basics.html

    【讨论】:

    • 非常感谢,m_x。我按照您的建议重写了我的模型,它们看起来更简单。我仍然想知道为什么 Rails 3 自动 html 转义会干扰我的数组。
    • 老实说,这远远超出了我的知识范围,但我认为您可以通过搜索有关 ActiveRecord 序列化的信息找到有关它的线索,请参阅api.rubyonrails.org/classes/ActiveRecord/Base.html(“将数组、哈希和其他不可映射的对象保存在文本列")
    • 好的,我想我明白了。当您尝试将数组保存在文本字段中时,AR 会在 YAML 中对其进行序列化,因为字段开头的“---”似乎表明了这一点。您可以在此示例中看到类似的连字符:blog.jayfields.com/2007/03/…。哦,只是说,您应该尝试使用 ruby​​ 块和迭代器而不是这些“for ... in”循环,您会惊讶于它们的强大功能!小例子:User.all.each {|friend| puts friend.username } 将显示所有用户名,User.all.collect &amp;:username 将它们全部填充到一个数组中...
    • 非常感谢您的跟进,m_x。我将根据您的线索深入研究 YAML。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多