Button to update status attribute of a table
Mission: add buttons to change the status
of a post
HOWTO:
migration - add status
column to posts
add_column :posts, :status, :string, null: false, default: "planned"
post.rb - list available statuses
validates :status, presence: true
STATUSES = %i[planned progress done].map(&:to_s).freeze
validates :quote_requestor, inclusion: { in: Post::STATUSES }
posts_controller.rb - add action to change status
def change_status
@post = Post.find(params[:id])
if params[:status].present? && Post::STATUSES.include?(params[:status].to_sym)
@post.update(status: params[:status])
end
redirect_to @post, notice: "Status updated to #{@post.status}"
end
routes.rb
resources :posts do
member do
patch :change_status
end
end
posts/show.html.erb
<% Post::STATUSES.each do |status| %>
<%= link_to change_status_post_path(@post, status: status), method: :patch do %>
<%= status %>
<% end %>
<% end %>
or with a block
<% Post::STATUSES.each do |status| %>
<%= link_to_unless post.status.eql?(status.to_s), status, change_status_post_path(post, status: status), method: :patch %>
<% end %>
Did you like this article? Did it save you some time?
You might also like:
- RE-REVISED: Polymorphism 101. Part 5 of 3. Even better Polymorphic Comments
- REVISED: Polymorphism 101. Part 4 of 3. Polymorphic Comments
- Polymorphism 101. Part 3 of 3. ActsAsTaggable without a gem. SelectizeJS
- Polymorphism 101. Part 2 of 3. Polymorphic Payments inside-out.
- Polymorphism 101. Part 1 of 3. Polymorphic Comments.