Skip to content

Instantly share code, notes, and snippets.

@kalleth
Created April 28, 2013 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kalleth/5476621 to your computer and use it in GitHub Desktop.
Save kalleth/5476621 to your computer and use it in GitHub Desktop.
# my controller
def create
@uid = Uid.find_by(number: uid_params[:number])
if @uid
update
else
@uid = Uid.new(uid_params)
if @uid.save
puts "Uid is #{@uid.inspect}"
flash[:success] = "Successfully created post"
redirect_to uids_path
else
@uids = Uid.paginate(page: params[:page])
render :index
end
end
end
def update
@uid = Uid.find_by(number: uid_params[:number])
if @uid.update_attributes(uid_params)
flash[:success] = "Successfully created post"
redirect_to uids_path
else
@uids = Uid.paginate(page: params[:page])
render :index
end
end
# my modal
class Uid < ActiveRecord::Base
before_save :check_number_validity
has_many :microposts, dependent: :destroy, autosave: true
accepts_nested_attributes_for :microposts
validates :number, presence: true, length: { is: 12 }, format: { with: /\A\d{12}\z/ }, uniqueness: true
private
def check_number_validity
# to check for number validity
true
end
end
# my micropost model
class Micropost < ActiveRecord::Base
belongs_to :uid
default_scope -> { order('created_at DESC') }
validates :content, presence: true, length: { maximum: 256 }
validates :uid_id, presence: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment