我有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"
我的问题是:我应该如何记录:“7”,“8”,“10”?
非常感谢你的帮助!
P / S:我在这里遵循教程:http://www.novawave.net/public/rails_messaging_tutorial.html
答案 0 :(得分:0)
您不应使用单个字段来保存对多个收件人的引用。相反,您的模型应如下所示:
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