添加属性以跟踪订户号码 - Rails

时间:2016-06-28 01:53:36

标签: ruby-on-rails

我目前在Subscriber上有一个名为mug_number的属性,其数据类型是整数。我有一个页面,一个人可以注册成为订阅者,每当一个人注册我想要这个数字增加1,以便在索引中我可以看到每个人的数字。为了清楚起见,我会发布代码。

SUBSCRIBER CONTROLLER:

  class SubscribersController < ApplicationController
  helper_method :sort_column, :sort_direction

  def index
    @search = Subscriber.search(params[:q])
    @subscriber = @search.result
    @search.build_condition if @search.conditions.empty?
    @search.build_sort if @search.sorts.empty?
  end

  def new
    @subscriber = Subscriber.new
  end

  def create
    @subscriber = Subscriber.create(subscriber_params)
    if @subscriber.save
      flash[:notice] = "Subscriber Has Been Successfully Created"
      redirect_to new_subscriber_path(:subscriber)
    else
      render "new"
    end
  end

SCHEMA:

 create_table "subscribers", force: :cascade do |t|
    t.string   "first_name"
    t.string   "last_name"
    t.string   "email"
    t.string   "phone_number"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.integer  "visit"
    t.integer  "mug_number"
  end

正如您在架构中看到的那样,mug_number

上有Subscriber属性

现在我正在尝试为表单添加一个hidden_​​field,但我不认为这是正确的实现?

FORM:

 <%= form_for @subscriber do |form| %>
    <div class="form-group">
      <p>
      <%= form.text_field :first_name, placeholder: "First Name", class: "text_field" %>
      </p>
      <p>
      <%= form.text_field :last_name, placeholder: "Last Name", class: "text_field" %>
      </p>
      <p>
       <%= form.text_field :phone_number, placeholder: "phone", class: "text_field" %>
      </p>
      <p>
      <%= form.text_field :email, placeholder: "Email", class: "text_field" %>
      </p>
      <%= form.hidden_field :mug_number %>
    </div>
    <%= form.submit "Sign Up", class: "btn" %>
  <% end %>

这应该是一个简单的故事,但由于某种原因我似乎无法弄明白?任何帮助都会很棒!

1 个答案:

答案 0 :(得分:1)

您不需要隐藏字段,因为您不想在保存记录之前生成数字。

before_create模型上的Subscriber回调应该可以。

class Subscriber < ActiveRecord::Base
  before_create :generate_mug_number

private

  def generate_mug_number
    last_number = Subscriber.maximum(:mug_number) || 0
    self.mug_number = last_number + 1
  end
end