Rails 5:find_or_create_by不保存所有参数

时间:2019-01-11 16:34:28

标签: ruby-on-rails ruby ruby-on-rails-5

我有一个应该发送信息的表格。输入之一是“ empresa_id”,由一个集合表示。我已经在服务器中检查了发送我想要的信息的表格。事情是,当我运行find_or_create_by时,不会保存该字段(只有那个)。我检查了强大的参数,那里的一切似乎都很好。

SuscriptorsController

  def create
    @suscriptor = Suscriptor.new(suscriptor_params)

    byebug #In this point @suscriptor.empresa_id has a correct value
    if !@suscriptor.valid?
      flash[:error] = "El email debe ser válido"
      render 'new'
    else
      @suscriptor = Suscriptor.find_or_create_by(email: @suscriptor.email)
      if @suscriptor.persisted?
        if (@suscriptor.email_confirmation == true)
          flash[:notice] = "Ya estás registrado/a"
          redirect_to root_path
        else
          SuscriptorMailer.registration_confirmation(@suscriptor).deliver
        end
      else
        flash[:error] = "Ha ocurrido un error. Contáctanos desde la sección contacto y explícanos"
        render 'new'
      end
    end


  private
  def suscriptor_params
    params.require(:suscriptor).permit(:email, :email_confirmation, :token_confirmation, :subtitle, :empresa_id)
  end

表单视图

<%= simple_form_for(@suscriptor) do |f| %>

<div class="input-group">
  <div class="col-md-12">

    <div class="form-group text">
      <%= f.input :email, class: "form-control", placeholder: "tucorreo@email.com", required: true %>
      <%= f.invisible_captcha :subtitle %>
      <small id="emailHelp" class="form-text text-muted">Lo guardaremos y usaremos con cuidado.</small>

      <%= f.input :empresa_id, collection: Empresa.all %>
    </div>


    <div class="input-group-append">
      <%= f.submit "¡Hecho!", class: "btn btn-primary" %>
    </div>
  </div>
<% end %>

schema.rb

  create_table "suscriptors", force: :cascade do |t|
    t.string   "email"
    t.boolean  "email_confirmation"
    t.string   "token_confirmation"
    t.datetime "created_at",         null: false
    t.datetime "updated_at",         null: false
    t.integer  "empresa_id"
  end

suscriptor.rb

class Suscriptor < ApplicationRecord
  belongs_to :empresa, optional: true

  before_create :confirmation_token
  attr_accessor :subtitle

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

  validates :email, presence: true, length: { maximum: 255 }, uniqueness: { case_sensitive: false }, format: { with: VALID_EMAIL_REGEX }

  def confirmation_token
      if self.token_confirmation.blank?
          self.token_confirmation = SecureRandom.urlsafe_base64.to_s
      end
  end

end

1 个答案:

答案 0 :(得分:2)

在您的find_or_create_by中,您仅传递@suscriptor.email,然后使用创建的脚本重新确定@suscriptor变量。

根据API基座,您应该传递一个块以“使用更多参数创建”:

Suscriptor.find_or_create_by(email: @suscriptor.email) do |suscriptor|
  suscriptor.empresa_id = @suscriptor.empresa_id
end

在使用参数之前,请注意不要重新分配@suscriptor变量。

您可以在https://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_create_by中阅读有关find_or_create_by的更多信息

希望这会有所帮助!