Skip to content

Instantly share code, notes, and snippets.

@cybersamx
Last active August 29, 2015 14:07
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 cybersamx/0fc2b968a08a4dfb55fd to your computer and use it in GitHub Desktop.
Save cybersamx/0fc2b968a08a4dfb55fd to your computer and use it in GitHub Desktop.
Rails select_tag and data validation
<%= form_for @my_model, html: { class: 'form-horizontal' } do |f| %>
<%= f.label :id, class: 'control-label %>
<div class="controls">
<%= f.select(:id, MyModel.all.pluck(:name, :id), include_blank: 'Select') %>
</div>
<% end %>
class MyModel < ActiveRecord::Base
# ID can't be null or blank.
validates :id, presence: true, allow_blank: false
end
class MyModelontroller < ApplicationController
def edit
end
def update
if @my_model.update(my_model_params)
# Updated successfully.
redirect_to my_model_path(@my_model), notice: 'Model was successfully updated.' }
else
# Fail to update, eg. id is blank.
if @my_model.errors.any?
flash[:error] = @my_model.errors.full_messages.first
end
render action: 'edit'
end
end
private
def my_model_params
params[:my_model].permit! # Permit all fields.
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment