2016年11月16日 星期三

從 view 回溯 controller 的 CRUD 筆記

controller 裡有七個 action,對應到view的動作

這篇記錄從 view 回溯 controller 的 CRUD 筆記(這些動作加起來就是CRUD了)

index
# app/views/groups/index.html.erb
<% @groups.each do |group| %>
  <%= link_to(group.title, group_path(group)) %>
  <%= group.description %>
<% end %>
上面 @groups,來自
# app/controllers/groups_controller.rb (以下皆同)
def index
    @groups = Group.all
  end


new和edit,則用 form 或 simple_form 傳回去
<%= simple_form_for @group do |f| %>
上面 @group,來自
def new
    @group = Group.new
  end
def edit
    @group = current_user.groups.find(params[:id])
  end
(new action 和create action是一組的;前者負責生出一筆新的資料,後者則是把網頁的這筆新資料填回資料庫,共用new.html.erb。
edit/update 和 new/create 的關係差不多,後者填回去資料庫,共用 edit.html.erb。
所以你看不到create和update的view )


show
# 點 app/views/groups/index.html.erb 的 title
# 會進入 app/views/groups/show.html.erb
上面 show 的 @group,來自
def index
    @groups = Group.all
  end


delete 沒有另開view頁面,放在上面 index 的 <% @groups.each do |group| %>裡
  <%= link_to("Delete", group_path(group), class: "btn btn-sm btn-default",
                 method: :delete, data: { confirm: "Are you sure?" }) %>

原則上就是,controller裡的action實例變數,這個實例變數,在和action同名的view中使用。

程式參考:rails 101

關於實例變數的說明,可以參考這位大大的文章:
Rails新手易混淆的變數使用

這篇文還說明 params[:id] 和Group開頭大寫的意思,值得新手一看。

沒有留言:

張貼留言