我正在尝试创建一个电子邮件记录,可以将其保存为不同的类型。例如,将发送给所有用户的电子邮件,或仅发送给某些作者的电子邮件。
除了编写者之外,每个选项都有效,我试图使用复选框来保存id数组,而不是从数据库中检索id数组。
class Email < ActiveRecord::Base
validates_presence_of :subject, :body
serialize :user_ids
after_create :set_user_ids
...
private
def set_user_ids
if mass_email?
array = User.pluck(:id)
elsif user_email?
...
end
self.user_ids ||= array
self.max_mailings = user_ids.size
save!
end
end
表单(使用simple_form):
<%= simple_form_for [:admin, @email] do |f| %>
<% if writers?(params[:email_type]) %>
<%= f.input :sent_to, as: :hidden, input_html: { value: "Writers" } %>
<%= f.input :user_ids, collection: Writer.all.collect{ |w| [w.name, w.id] }, as: :check_boxes, label: false %>
<br>
<% end %>
...
<% end %>
html:
<form accept-charset="UTF-8" action="/admin/emails" class="simple_form new_email" id="new_email" method="post" novalidate="novalidate">
...
<div class="control-group check_boxes optional email_user_ids">
<div class="controls">
<label class="checkbox">
<input class="check_boxes optional" id="email_user_ids_1" name="email[user_ids][]" type="checkbox" value="1" />
John Smith
</label>
<label class="checkbox">
<input class="check_boxes optional" id="email_user_ids_2" name="email[user_ids][]" type="checkbox" value="2" />
Bob Brown
</label>
<input name="email[user_ids][]" type="hidden" value="" />
</div>
</div>
通常的new
和create
操作:
class Admin::EmailsController < ApplicationController
def new
@email = Email.new
end
def create
@email = Email.new(email_params)
if @email.save
flash[:success] = "Email saved successfully."
redirect_to [:admin, @email]
else
render 'new'
end
end
private
def email_params
params.require(:email).permit(:subject, :body, :email_type, :user_ids, :max_mailings, :sent_to)
end
end
但是当我尝试提交以下错误时,即使存在user_ids
参数:
undefined method 'size' for nil:NilClass
Extracted source (around line #51):
49 end
50 self.user_ids ||= array
51 self.max_mailings = user_ids.size
52 save!
53 end
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"cVyUQY7Faqr6JpkdGoPwLhe+Pv6ld/7vzXLvBg+tzsk=",
"email"=>{"sent_to"=>"Writers",
"user_ids"=>["1",
"2",
""],
"subject"=>"Email to writers",
"body"=>"Email to writers",
"email_type"=>"writers"},
"commit"=>"Create Email"}
我无法弄清楚为什么user_ids
未正确更新
此外,我不确定为什么额外的email[users_id][]
字段会呈现为隐藏字段。
答案 0 :(得分:4)
我相信您的问题可能在于您的email_params方法。查看how to permit an array with strong parameters。看起来您可能需要明确声明user_ids将是一个数组。