1

RoR 애플리케이션에서 필자는 전자 메일,받는 사람 및 연락처라는 모델을 가지고 있습니다. 따라서 새 전자 메일을 만들 때 사용자는 전자 메일을 보낼 연락처를 선택합니다. 수신자 테이블에 저장; like :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 모델 : 나는 다른 SO 질문을 살펴 보았다

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 

포함 :

  • Validate a belongs to association in a build situation
  • 그러나이 같은 문제를 해결하지 못하는 것 같습니다.

    답변

    0

    내가하고 싶은 일은 전자 메일 양식에 유효성 검사를 추가하여 사용자가 전자 메일을 보낼 연락처를 선택했는지 확인하는 것입니다.

    .build을 사용해야합니까? 이것으로 협회의 존재를 검증 할 필요가있는 것처럼 보입니다. 이처럼 :

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

    Source

    아니면 내가 뭔가를 놓친 거지?