mardi 7 mars 2017

Ruby on Rails: Validate checkboxes in build relationship

In my RoR application, I have the models Emails, Recipients, and Contacts, whereby when creating a new email the user selects the contacts they want to send the email to, and these are saved in the recipients table; like so:

 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

What I want to do is add validation on the email form to ensure that a user has selected contacts to send the email to. However, I cannot work out how to do this with the builds relationship, can someone please help?

My emails_controller is:

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

The form:

<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>

The Email.rb model:

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

I have looked at other SO questions, including:

But these do not seem to address the same problem.

Aucun commentaire:

Enregistrer un commentaire