mr_muscle
mr_muscle

Reputation: 2900

Rails create record with status published if all parameters are set

My Event model has following fields:

  create_table "group_events", force: :cascade do |t|
    t.date "start_date", null: false
    t.date "end_date
    t.string "name"
    t.string "description"
    t.string "status", default: "draft"

I've got a requirement that the event should be draft or published. To publish all of the fields are required, it can be saved with only a subset of fields before it’s published. How to recognize if a record should be saved as a draft or published?

  def create_event
    Event.create!(
      start_date: params[:start_date],
      end_date: params[:end_date],
      name: params[:name],
      description: params[:description],
      user_id: params[:user_id]
    )
  end

Should I count params and based on that set status in create_event method or is there any better way to do so?

Upvotes: 0

Views: 101

Answers (1)

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11915

You could register a before_save ActiveRecord callback to set the status to published if the event is publishable.


# app/models/event.rb

class Event < ApplicationRecord
  before_save :set_status

  private

  def set_status
    self.status = 'published' if publishable?
  end

  def publishable?
    [
      name,
      description,
      end_date
    ].all?(&:present?) # Add other fields as required. `start_date` is omitted since it's required.
  end
end

Upvotes: 2

Related Questions