coding with alpaca -43 發起提案 (purchase)

rails g model purchase

修改 migration:

class CreatePurchases < ActiveRecord::Migration[5.1]
def change
create_table :migrations do |t|

t.string :time_period
t.datetime :end_time
      # relationship
      t.belongs_to :store, index: true
t.belongs_to :user, index: true
      t.timestamps
end
end
end

Purchase.rb

belongs_to :user
belongs_to :store

store.rb

has_many :purchases

user.rb

has_many :purchases

終端機:

rails g controller purchases

config/routes.rb

resources :purchases

rails g controller purchases

到 purchases_controller

before_action :authenticate_user!
def new
@purchase = Purchase.new
end

purchases/new.html

<%= form_for @purchase do |f| %>
  <%= f.label :time_period, '時段' %>
<%= f.select :time_period, ['早餐', '午餐', '晚餐'] %>
  <%= f.label :store_id, '店家'%>
<%= f.collection_select :store_id, Store.all, :id, :name %>
  <%= f.label :end_time, '截止日期' %>
<%= f.datetime_select :end_time %>
  <%= f.submit '送出提案' %>
<% end %>

collection_select 的標準寫法:

<%= f.collection_select :想要傳入的欄位名稱, 集合, :給電腦看的欄位(跟集合有關), :給人看的欄位(跟集合有關) %>

改系統預設時區

到 config/application.rb,新增:

config.time_zone = "Taipei"

Form control in Bulma

.field>.control>.select

PurchaseController.rb

class PurchasesController < ApplicationController
  before_action :authenticate_user!
  def new
@purchase = Purchase.new
end
  def create
@purchase = current_user.purchases.build purchase_params
if @purchase.save
redirect_to purchases_path
else
render 'new'
end
end
private
def purchase_params
params.require(:purchase).permit(:store_id, :time_period,
:end_time)
end
end

這裏不用 new, 用 current_userbuild

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.