我一直在關注Brandon Tilley's instructions on creating a private message system,並且想要修改私人消息收件人的傳遞方式(從複選框到文本框)。如何將數組從表單傳遞給控制器?
在視圖我有這樣的:
<%= f.label :to %><br />
<%= f.text_field :to, placeholder: "Recip...(separated by commas)" %>
如何可以接受輸入作爲通過整數數組到所述控制器的文本輸入?
額外的細節:
完整視圖:
<h1>New Conversation</h1>
<%= form_for(@conversation) do |f| %>
<div>
<%= f.label :to %><br />
<%= f.text_field :to, placeholder: "Recip...(separated by commas)" %>
</div>
<br />
<%= f.fields_for :conversation do |c| %>
<div>
<%= c.label :subject %>
<%= c.text_field :subject %>
</div>
<%= c.fields_for :messages do |m| %>
<div>
<%= m.label :body %><br />
<%= m.text_area :body %>
</div>
<% end %>
<% end %>
<%= f.submit %>
<% end %>
內的控制器我有這樣的:
def create
redirect_to users_path unless current_user
@conversation = UserConversation.new(params[:user_conversation])
@conversation.user = current_user
@conversation.conversation.messages.first.user = current_user
...
在模型中我有這樣的:
accepts_nested_attributes_for :conversation
delegate :subject, :to => :conversation
delegate :users, :to => :conversation
attr_accessor :to
*before_create :create_user_conversations*
private
def create_user_conversations
return if to.blank?
to.each do |recip|
UserConversation.create :user_id => recip, :conversation => conversation
end
end
end
編輯:新型號:
def to
to.map(&:user_id).join(", ") *stack too deep error*
end
def to=(user_ids)
@to = user_ids.split(",").map do |recip|
UserConversation.create :user_id => recip.strip, :conversation => conversation
end
感謝您的答覆。我沒有運氣就試過你的代碼,所以採用了與編輯問題中提到的另一種方法相同的想法。沒有發生錯誤,但user_ids是空白的。你能解釋你的代碼嗎? – 2013-02-11 18:14:20
您的解決方案是錯誤的組合。你可以使用帶逗號分隔值的text_field,並在'to'訪問器中使用轉換,或者如果在「user_conversation [to] []」上使用複選框,則不需要爲'to'轉換。不過,在這兩種情況下,請確保您允許'to'參數的大量分配。 – 2013-02-11 18:22:57