This time, I had the opportunity to update the status using enum, and I implemented it while struggling with various investigations. I will write about enums.
Ruby : 2.6.3 Ruby on Rails : 5.2.4
Enum can form an array, store data in the column in advance, and manage acquisition and update. It is used when the number of data and options are decided like this time.
When I implemented it, I referred to this article. -[Rails] What is an enum? I made a select box using an enum. https://qiita.com/clbcl226/items/3e832603060282ddb4fd
This time, the order model (order) and the related order product model (order_product) have the following status. We will implement them so that they work together, but this time we will omit them. The writing method is simple and the key has a value.
order.rb
belongs_to :customer
has_many :order_products, dependent: :destroy
enum status: {
Waiting for payment: 0,
Payment confirmation: 1,
In production: 2,
Preparing to ship: 3,
sent: 4
}
order_product.rb
belongs_to :order
belongs_to :product
enum making_status: {
Cannot be manufactured: 0,
Waiting for production: 1,
In production: 2,
Production completed: 3
}
When updating the status, I used form_with to write as follows.
orders/show.html.erb
<%= form_with model: order, url: admin_order_path(order), class:"update_status" do |f| %>
<%= f.select :status, Order.statuses.keys %>
<%= f.submit "update", class:'btn btn-info' %>
<% end %>
orders_controller.rb
class Admin::OrdersController < ApplicationController
def update
order = Order.find(params[:id])
order.update(status: order.status)
redirect_to admin_order_path(order)
end
end
In this case, for example, if you select "Payment Confirmation" in the view and update it, the character string "Payment Confirmation" will be passed as it is to the parameter. It works fine, but I was wondering why it is not possible to transfer data numerically even though it is managed by enum.
orders/show.html.erb
<%= form_with model: order, url: admin_order_path(order), class:"update_status" do |f| %>
<%= f.select :status, options_for_select(Order.statuses.to_a, selected: order.status_before_type_cast) %>
<%= f.submit "update", class:'btn btn-info' %>
<% end %>
So, I tried to write the value to be passed as a numerical value like this, In this case, it was passed as a String type and the data could not be updated.
As a result of various investigations, it seems that it is necessary to convert what was passed in String type to Integer type in the controller.
orders_controller.rb
order = Order.find(params[:id])
status = params[:order][:status].to_i
order.update(status: status)
redirect_to admin_order_path(order)
You have successfully updated the data with numerical values! I wish I could make it a little more concise (maybe)
There may be various opportunities to use it in the future, so I want to acquire it firmly. We would appreciate it if you could comment if there are any deficiencies or mistakes in the content.
Recommended Posts