Ruby on Rails:验证构建关系中的复选框

时间:2017-03-03 13:33:40

标签: ruby-on-rails ruby ruby-on-rails-3 validation ruby-on-rails-4

在我的RoR应用程序中,我有模型电子邮件,收件人和联系人,在创建新电子邮件时,用户选择他们要发送电子邮件的联系人,这些联系人保存在收件人表中;像这样:

 Emails
 Id       Subject
 1        Conference
 2        Monday Office

 Recipients
 Id      Email_Id     Contact_Id
 1       1            3
 2       1            1
 3       2            2
 4       2            1

 Contacts
 Id      Name
 1       Ben
 2       Tom
 3       Trevor

我想要做的是在电子邮件表单上添加验证,以确保用户选择了要发送电子邮件的联系人。但是,我无法弄清楚如何使用构建关系来做这件事,有人可以帮忙吗?

我的emails_controller是:

def new
    session[:email_params] ||= {}
    @email = Email.new(session[:email_params])
    @email.current_step = session[:email_step]
    @email.recipients.build
    @useraccounts = Useraccount.where(user_id: session[:user_id])
    @contacts = Contact.where(user_id: session[:user_id], subscription: true)
    @templates = Template.all
end

表格:

<div class="form-group">
    <label>From Email Address</label></br>
    <% @useraccounts.each do |useraccount| %>
        <%= f.radio_button :account_id, useraccount.account_id, :checked => false %>
        <%= f.label :account_id, useraccount.account.email, :value => "true"  %> <br>
    <% end %>
</div>
<div class="form-group">
    <label>Contacts</label></br>
    <%= f.collection_check_boxes :contact_ids, @contacts, :id, :fullname %>
</div>
<div class="form-group">
    <label>Attachment</label>
    <%= f.file_field :attachment, :size => 42 %><br>
</div>

Email.rb型号:

class Email < ActiveRecord::Base
    attr_writer :current_step
    belongs_to :account
    belongs_to :template
    has_many :recipients
    has_many :contacts, through: :recipients, :dependent => :destroy

    validates :subject, :presence => { :message => "Please enter a subject" }, :if => lambda { |o| o.current_step == "email_content" }
    validates :message, :presence => { :message => "Please enter a message" }, :if => lambda { |o| o.current_step == "email_content" }
    validates :template_id, :presence => { :message => "Please select a template" }, :if => lambda { |o| o.current_step == "email_template" }
    validates :account_id, :presence => { :message => "Please select an account to send the email from" }, :if => lambda { |o| o.current_step == "email_recipients" }
end

我已经查看了其他SO问题,包括:

但这些似乎并没有解决同样的问题。

1 个答案:

答案 0 :(得分:0)

  

我想要做的是在电子邮件表单上添加验证,以确保用户选择了要发送电子邮件的联系人。

为什么要使用.build?从这看起来你只需要验证关联的存在。 像这样:

class Email < ActiveRecord::Base
  ...
  has_many :recipients
  validates :recipients, presence: true
  ...

Source

或者我错过了什么?