Rails User Mailer:向嵌套资源发送多封电子邮件。

时间:2016-01-07 08:44:33

标签: ruby-on-rails ruby

我将嵌套资源放置在嵌套表单中(用于电子邮件输入),并希望使用User Mailer发送电子邮件。 我在完成以下挑战时遇到问题:

1)在我的邀请/新页面上有10个输入字段:fields_for,以便一次最多发送10封电子邮件。

2)提交后,循环显示已提交的电子邮件,并向每个提交的条目发送电子邮件。

3)发送完电子邮件后,我没有使用数据库中的@invitation并希望销毁它。

到目前为止,我有以下代码:

模特

class Scoreboard < ActiveRecord::Base

has_many :invitations

accepts_nested_attributes_for :invitations

end

class Invitation < ActiveRecord::Base

  belongs_to :scoreboard     

  def send_invitation_email
    UserMailer.send_invitation(self).deliver_now
  end

end

new.html.erb(邀请)

 <%= form_for [@scoreboard, @invitation] do |f| %> 
        <%= render 'shared/error_messages', object: f.object %>

       <%= f.fields_for :invitations do |invites| %> <!-- this gives me one field. Need 10 fields to accept up to 10 emails -->
         <div>
         <%= invites.label :recipient_email %> 
         <%= invites.text_field :recipient_email %> 
         </div>
       <% end %>

        <%= f.submit "Send Invitation", class: "btn btn-primary" %>
    <% end %>

邀请控制器

class InvitationsController < ApplicationController

    def new
        @scoreboard = Scoreboard.find(params[:scoreboard_id])
        @invitation =  @scoreboard.invitations.build 
    end

    def create
    @scoreboard = Scoreboard.find(params[:scoreboard_id])
    @invitation = @scoreboard.invitations.build(invitation_params)

    if @invitation.save
      @invitation.send_invitation_email
      flash[:success] = "Invitation sent successfully"
      redirect_to new_scoreboard_invitation_path
    else
        render 'new'
    end
    end


private

def invitation_params
    params.require(:invitation).permit(:recipient_email)
end

end

当我提交表单时,在开发日志中,我得到以下示例代码:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"gS+olMC89noaYs0klYTg6IFgJ2cj4apML/NZbdbu2gia/KXjbPyyvSKrEUoj3rEAWxDknlgNmpnaefy7I6Hk3Q==", "invitation"=>{"invitations"=>{"recipient_email"=>"this@hotmail.com "}}, "commit"=>"Send Invitation", "scoreboard_id"=>"89"}

使用哈希中可能的哈希集合的逻辑,我在User Mailer文件中提出了以下代码:

user_mailer.rb

def send_invitation(invitation)
    @invitation = invitation
    @invitation.each do |key, value|
      value.each do | x, y|
        mail to: y , subject: "You have been invited"
      end
    end
  end

提前致谢!

可选奖金问题:

send_invitation.html.erb

<p>Hi View this Thanks </p> <br></br>
<%= # if someone could provide me a code to a link_to for the url for the scoreboard that the invitation is attached to that would be awesome %>

0 个答案:

没有答案