1
在我的RoR应用程序中,我有模型Emails,Recipients和Contacts,当创建新电子邮件时,用户选择他们想要发送电子邮件的联系人,这些是保存在收件人表中;像这样:Ruby on Rails:验证构建关系中的复选框
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
我已经看过其他等问题,包括:
- Creating association with .build and working around parameter validation
- Validate a belongs to association in a build situation
- build method on ruby on rails
但这些似乎并没有解决同样的问题。