【问题标题】:Ruby on Rails: Validate checkboxes in build relationshipRuby on Rails:验证构建关系中的复选框
【发布时间】:2017-03-03 13:33:40
【问题描述】:

在我的 RoR 应用程序中,我有 Emails、Recipients 和 Contacts 模型,在创建新电子邮件时,用户可以选择他们想要向其发送电子邮件的联系人,并将它们保存在收件人表中;像这样:

 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 问题,包括:

但这些似乎不能解决同样的问题。

【问题讨论】:

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


    【解决方案1】:

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

    为什么使用.build?由此看来,您只需要验证关联的存在即可。 像这样:

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

    Source

    还是我错过了什么?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多