Продолжайте получать "неопределенный метод` email 'для nil: NilClass ", что я делаю не так? - PullRequest
1 голос
/ 10 января 2020

Так вот как выглядит мой контроллер. Я хочу нажать кнопку и отправить электронное письмо на текущую цитату. Если я помещаю туда строковое письмо, оно работает, но когда я заменяю его, чтобы @ quote.email извлекал письмо из текущего объекта, я получаю эту ошибку:

"undefined метод` email 'для nil : NilClass "

Я понятия не имею, почему это делает, кто-то, пожалуйста, помогите!

class QuotesController < ApplicationController

  require 'sendgrid-ruby'
  include SendGrid

  before_action :set_quote, only: [:show, :edit, :update, :destroy]

  # GET /quotes
  # GET /quotes.json
  def index
    @quotes = Quote.all
  end

  def thankyoupage
  end

  # GET /quotes/1
  # GET /quotes/1.json
  def show
  end

  # GET /quotes/new
  def new
    @quote = Quote.new
  end

  # GET /quotes/1/edit
  def edit
  end

  # POST /quotes
  # POST /quotes.json
  def create

    @quote = Quote.new(quote_params)

    if @quote.save
      redirect_to thankyou_path
    else
      redirect_to root
    end

  end

  # PATCH/PUT /quotes/1
  # PATCH/PUT /quotes/1.json
  def update
    respond_to do |format|
      if @quote.update(quote_params)
        format.html { redirect_to @quote, notice: 'Quote was successfully updated.' }
        format.json { render :show, status: :ok, location: @quote }
      else
        format.html { render :edit }
        format.json { render json: @quote.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /quotes/1
  # DELETE /quotes/1.json
  def destroy
    @quote.destroy
    respond_to do |format|
      format.html { redirect_to quotes_url, notice: 'Quote was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  def sendQuoteEmail

    from = SendGrid::Email.new(email: 'email@joinbennett.com')
    to = SendGrid::Email.new(email: @quote.email)
    subject = 'Sending with Twilio SendGrid is Fun'
    content = SendGrid::Content.new(type: 'text/plain', value: 'and easy to do anywhere, even with Ruby')
    mail = SendGrid::Mail.new(from, subject, to, content)

    sg = SendGrid::API.new(api_key: '*****************')
    response = sg.client.mail._('send').post(request_body: mail.to_json)
    puts response.status_code
    puts response.body
    puts response.headers

  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_quote
      @quote = Quote.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def quote_params
      params.fetch(:quote, {}).permit(:first_name, :last_name, :phone_number, :address, :email, :quote_date, :quote_time, :quote_bedroom, :quote_bathroom, :quote_notes, :quote_price, :quote_price_recurring)
    end
end

Когда создается цитата, у нее есть электронное письмо. Я создал эту кнопку для запуска этого действия под названием SendQuoteEmail.

<%= button_to 'Send Quote Email', quotes_sendQuoteEmail_path, method: :post, class: 'btn btn-success mt-3' %>

Что я делаю не так? Я продолжаю говорить, что @ quote.email - это NIL ??

Ответы [ 2 ]

3 голосов
/ 10 января 2020

в вашем контроллере, обновите эту строку:

before_action :set_quote, only: [:show, :edit, :update, :destroy, :sendQuoteEmail]

, затем, по вашему мнению, передайте идентификатор. quotes_sendQuoteEmail_path (: id => @ quote.id)

<%= button_to 'Send Quote Email', quotes_sendQuoteEmail_path(:id => @quote.id), method: :post, class: 'btn btn-success mt-3' %>
1 голос
/ 10 января 2020

Измените:

  before_action :set_quote, only: [:show, :edit, :update, :destroy]

на

  before_action :set_quote, only: [:show, :edit, :update, :destroy, : sendQuoteEmail]

Это позволит Rails запустить метод set_quote, который позволит контроллеру найти объект @quote перед тем, как вы на него воздействуете.

Добавить @quote в помощник пути:

<%= button_to 'Send Quote Email', quotes_sendQuoteEmail_path(@quote) ...
...