Skip to content

Instantly share code, notes, and snippets.

@negabaro
Last active September 19, 2017 14:02
Show Gist options
  • Save negabaro/370cbad7418d6963c08ece171b296d79 to your computer and use it in GitHub Desktop.
Save negabaro/370cbad7418d6963c08ece171b296d79 to your computer and use it in GitHub Desktop.
CRUD simple noticeboard with rails5.1
app/controller/articles_controller.rb
class ArticlesController < ApplicationController
before_action :set_article, only: [:show, :edit, :update, :destroy]
def show
end
def edit
end
def update
@article.assign_attributes(article_params)
if @article.valid?
@article.save!
flash[:success] = "success updated!!"
redirect_to @article
else
render 'edit'
end
end
def destroy
@article.destroy
flash[:success] = "success deleted!!"
redirect_to article_path
end
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
@article.save!
flash[:success] = "success created!!"
redirect_to @article
end
private
def set_article
@article = Article.find([params[:id]])
end
def article_params
params.require(:article).permit(:title, :body)
end
rails g controller articles
rails g model article title:string body:text
app/models/article.rb
class Article < ApplicationRecord
end
app/views/articles/edit.html.haml
= render 'form'
app/views/articles/form.html.haml
= bootstrap_form_for(@article) do |f|
= f.alert_message 'xxx'
= f.text_field :title, autofocus: true
= f.text_area :body, rows: 20
= f.button 'publish', name: 'ope[cmd]', value: 'publish', class: 'btn btn-lg btn-default'
= link_to 'delete', @article, :method => :delete, :data => {:confirm => "do u want to be deleted?"}, class: 'btn btn-danger btn-lg'
app/views/articles/new.html.haml
= render 'form'
app/views/articles/show.html.haml
%h1
= @article.tilte
= @article.body
%div
published date: #{@article.updated_at}
$div
= link_to 'modify', edit_article_path(@article), class: 'btn btn-default btn-lg'
= link_to 'delete', @article, :method => delete, :data => { :confirm => 'do u want to be deleted?'}, class: 'btn btn-danger btn-lg'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment