Last active
August 29, 2015 14:07
-
-
Save cybersamx/0fc2b968a08a4dfb55fd to your computer and use it in GitHub Desktop.
Rails select_tag and data validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= 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 %> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyModel < ActiveRecord::Base | |
# ID can't be null or blank. | |
validates :id, presence: true, allow_blank: false | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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