我的Rails表单未提交或重定向

时间:2019-01-24 08:43:11

标签: ruby-on-rails ruby

我的邀请表单未保存。没有错误。没有发送邮件,也没有将我重定向到根路径。

邀请控制器:

class InvitesController < ApplicationController
  def new
    @invite = Invite.new
  end

  def create
    @invite = Invite.new(invite_params)
    if @invite.save
      InviteMailer.invite_user(@invite).deliver_now
      flash[:success] = "You have successfully sent an invite"
      redirect_to root_path
    else
      render 'new'
    end
  end

  private

    def invite_params
      params.require(:invite).permit(:email)
    end
end

邀请模型:

class Invite < ApplicationRecord
  belongs_to :user
end

邀请新视图:

<h1>Invite your friend!</h1>
<%= form_for @invite , :url => userinvite_path do |f| %>
    <%= f.label :email %>
    <%= f.email_field :email %>
    <%= f.submit "Send" %>
<% end %>

邀请邮件发件人:

class InviteMailer < ApplicationMailer
  def invite_user(invite)
    @invite = invite
    mail to: invite.email, subject: "Invitation to Math-Scientist"
  end
end

应用程序邮件程序:

class ApplicationMailer < ActionMailer::Base
  default from: 'noreply@example.com'
  layout 'mailer'
end

邮件视图(文本):     你好     您的朋友已邀请您加入数学科学家。     立即注册:https://math-scientist.herokuapp.com/usersignup     希望您喜欢我们的产品!

路由文件:

Rails.application.routes.draw do
  root 'static_pages#home'
  get '/usersignup', to: 'users#new'
  get '/companysignup', to: 'companies#new'
  get    '/userlogin',   to: 'sessions#new'
  post   '/userlogin',   to: 'sessions#create'
  delete '/userlogout',  to: 'sessions#destroy'
  get '/userinvite', to: 'invites#new'
  post '/userinvite', to: "invites#create"
  resources :users
  resources :companies
  resources :invites
end

1 个答案:

答案 0 :(得分:1)

我猜该邀请没有被保存,因为您有belongs_to :user关系。由于导轨5,默认情况下是必需的。这意味着要么,要么您必须在保存之前设置user_id,或者将其指定为可选。

请勿在表单的隐藏字段中为用户ID设置表单,因为这会篡改(例如,有人在提交表单之前对其进行了编辑)。

因此,在您的控制器中,您可以执行类似

的操作
@invite = Invite.new(invite_params)
@invite.user_id = current_user.id 
if @invite.save ...

或者,如果确实不需要user,您也可以调整模型

belongs_to :user, optional: true