Action Mailer приглашает Rails 3.1 - PullRequest
       1

Action Mailer приглашает Rails 3.1

0 голосов
/ 14 декабря 2011

Используя в качестве опоры Ryan Bate's RailsCasts # 124 Beta Invites (а также обновленные rails 3.1 api), я пытаюсь собрать свою первую часть функциональности Action Mailer: пригласить кого-то сотрудничать с вами в проекте.

Моя проблема в том, что :recipient_email не сохраняется в БД, и я не вижу, что мне не хватает.

конфиг / Инициализаторы / setup_mail.rb

ActionMailer::Base.smtp_settings = {
  :address                    => "smtp.gmail.com",
  :port                       => 587,
  :domain                     => 'blah.com',
  :user_name                  => 'gmail username',
  :password                   => 'gmail password',
  :authentication             => 'plain',
  :enable_starttls_auto       => true
}

ActionMailer::Base.register_interceptor(DevelopmentMailInterceptor) if Rails.env.development?

приложение / модели / invitation.rb

class Invitation < ActiveRecord::Base

  email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :recipient_email

  belongs_to :sender, :class_name => "User", :foreign_key => "sender_id"
  has_one :recipient, :class_name => "User", :foreign_key => "recipient_id"

  validates_presence_of :recipient_email, :on => :create, :message => "can't be blank"
  validates :recipient_email, :format => email_regex
  validate :recipient_is_not_registered

  before_create :generate_token

  def sender_name
    sender.user_name
  end

  def sender_email
    sender.email
  end

  private

    def recipient_is_not_registered 
      exsisting_user = User.find_by_email(recipient_email)
      if exsisting_user
        errors.add :recipient_email, 'is already a member.'
      else
        recipient_email
      end
    end

    def generate_token
      self.token = Digest::SHA1::hexdigest([Time.now, rand].join)
    end

end

app / models / user.rb (минус все аутентичные данные)

class User < ActiveRecord::Base
  attr_accessible :invitation_token

  has_many :sent_invitations, :class_name => "Invitation", :foreign_key => "sender_id" 
  belongs_to :invitation

end

приложение / контроллер / invitations_controller.rb

class InvitationsController < ApplicationController
  before_filter :authenticate

  def new
    @title = "Invite client"
    @invitation = current_user.sent_invitations.new
  end

  def create
    @invitation = current_user.sent_invitations.create!(params[:invitation])
    sender_name = @invitation.sender_name
    sender_email = @invitation.sender_email
    if @invitation.save
      Mailer.invitation(@invitation, signup_url(@invitation.token), sender_name, sender_email).deliver
      flash[:success] = "Your client has been sent the email. Why not create a booking for them?"
      redirect_to bookings_path
    else
      @title = "Invite client"
      render :new
    end
  end

end

приложение / отправители / mailer.rb

  def invitation(invitation, signup_url, sender_name, sender_email)
    @signup_url = signup_url
    @sender_name = sender_name
    @sender_email = sender_email
    mail(:to => invitation.recipient_email, 
         :subject => "Invitation to Join",
         :from => @sender_email)
  end  

приложение / просмотров / приглашений / _invitation_form.html.erb

<%= form_for @invitation do |f| %>
    <%= render 'shared/error_messages', :object => f.object %>
    <%= f.hidden_field :email_token %>
    <br />
    <div class="field">
        <%= f.label :recipient_email, "Client's email address" %>
        <%= f.email_field :recipient_email %>
    </div>
    <br />
    <div class="action">
        <%= f.submit "Send invitation", :class => "a small white button radius" %>
    </div>
<% end %>

Журнал SQL, показывающий, что: receient_email не сохраняется

Started POST "/invitations" for 127.0.0.1 at 2011-12-14 21:27:11 +1100
  Processing by InvitationsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"7/SGZypGXtf9ShlcjC6o8ZRj2Qe4OJTHdjis2/m3ulc=", "invitation"=>{"recipient_email"=>"users@email.com"}, "commit"=>"Send invitation"}
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
   (0.1ms)  BEGIN
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."email" = 'users@email.com' LIMIT 1
  SQL (0.4ms)  INSERT INTO "invitations" ("created_at", "recipient_email", "sender_id", "sent_at", "token", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"  [["created_at", Wed, 14 Dec 2011 10:27:11 UTC +00:00], ["recipient_email", nil], ["sender_id", 1], ["sent_at", nil], ["token", "56fba1647d40b53090dd49964bfdf060228ecb2d"], ["updated_at", Wed, 14 Dec 2011 10:27:11 UTC +00:00]]
   (10.2ms)  COMMIT
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
   (0.1ms)  BEGIN
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."email" = 'users@email.com' LIMIT 1
   (0.1ms)  COMMIT
Rendered mailer/invitation.text.erb (0.4ms)

Sent mail to users@email.com (7ms)
Date: Wed, 14 Dec 2011 21:27:11 +1100
From: admin@email.com

1 Ответ

1 голос
/ 14 декабря 2011

Это, вероятно, линия attr_accessor :recipient_email в вашей Invitation модели.Возьмите эту строку, как recipient_email это поле базы данных, не так ли?

...