我一直在关注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
答案 0 :(得分:1)
rails helpers未设置为自动神奇地处理任意数组输入。
您可以使用多个复选框或解析文本输入,这是一个以逗号分隔的用户名列表。在你的模型中
def to=(string)
@to = User.where(:name => string.split(',')).select(:id).map(&:id)
end
为了获得更好的用户体验,您可以使用tagsinput jquery plugin和/或自动填充功能。
另请注意,如果您使用表单修改此同一对象,则需要将逗号分隔的字符串重新生成为:value选项,以便text_field输入正确预填充您的编辑表单。
<%= text_field_tag "user_conversation[to]", (@conversation.to || []).join(',') %>
答案 1 :(得分:0)
在视图中:
<%= f.label :to %><br />
<%= f.text_field :to, placeholder: "Recip...(separated by commas)" %>
在模型中:
attr_accessible :to
attr_accessor :to
before_create :create_user_conversations
private
to.split(",").each do |recip|
UserConversation.create :user_id => recip, :conversation => conversation
end