开发者

Error: ActiveRecord automatically escape input array from check_box_tag (Rails 3)

I have PrivateMessage model, whose :to field may contain multiple recipient ids.

create_table :private_messages do |t|
  t.integer :author_id
  t.string :subject
  t.text :body
  t.开发者_JS百科text :to
  t.timestamps

I use a check_box_tag to let sender choose recipients he wants to send to:

<% 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 %>

When user selects multiple recipients, the params passed 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"}

However, when the row is inserted to my table, it is automatically escaped as following:

  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')

When I check the record on my console:

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

My question is: how should I make a record of :to as "7", "8", "10"?

Thank you very much for your help!

P/S: I am following the tutorial here: http://www.novawave.net/public/rails_messaging_tutorial.html


you shouldn't use a single field to hold references to multiple recipients. Instead, your models should look like :

class PrivateMessage
  has_and_belongs_to_many :recipients
end

class Recipient
  has_and_belongs_to_many :private_messages
end

this way, your PrivateMessage and Recipient model will be associated via a third table (you dont have to bother about it, Rails does all the background stuff for you), and you'll get getters and setters like

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

or

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

It does not fully answer your question, but i think you should definitely look that way. I also warmly recommend you to read the RoR/AR guide about associations : http://guides.rubyonrails.org/association_basics.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜