在一个控制器中创建两个动作 - Rails

时间:2016-05-30 17:18:15

标签: ruby-on-rails

目前,我有一个Subscribers控制器,对订阅者执行了newindexcreate操作。这个功能现在非常基础。我还有一个subscriber模型,它接收包括phone_number在内的所有常规信息。我想要一个新表单,它将简单地接受订阅者phone_number并为我在订阅者模型上设置的特定订阅者添加1 visit整数。这是我目前的代码清晰。这是否可以基本更新键入其号码的订户并将1添加到访问整数?

CONTROLLER

 class SubscribersController < ApplicationController
def index
 @subscriber = Subscriber.all
end

def new
  @subscriber = Subscriber.new
end

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

 def visit
   @subscriber = Subscriber.find_by_phone_number(params[:phone_number])
 if @subscriber
   @subscriber.visit += 1
   redirect_to subscribers_visits_new_path(:subscriber)
 else
   render "new"
 end
end

MODEL

class Subscriber < ActiveRecord::Base
validates :first_name, presence: true
validates :last_name, presence: true
validates :email, presence: true
validates :phone_number, presence: true

def date_joined
  created_at.strftime("%-m/%-d/%-y")
end

def expiration_date
  (created_at + 1.year).strftime("%-m/%-d/%-y")
end
end

1 个答案:

答案 0 :(得分:1)

当然是。我建议使用你的行动网址(访问)进行创建。

然后在你的控制器中你只需要做

@subscriber.update_attribute(:visit, @subscriber.visit+1)