2015年9月8日 星期二

Cloud9-RoR-RESTful應用

參考文章:https://ihower.tw/rails4/restful.html

修改config/routes.rb,增加resources :events,
刪除match ':controller(/:action(/:id(.:format)))', :via => :all
resources :events
*在routes.rb裡面,越上面的路由規則越優先。

重要的表格:
Helper GET POST PATCH/PUT DELETE
event_path(@event) /events/1
show action
/events/1
update action
/events/1
destroy action
events_path /events
index action
/events
create action
edit_event_path(@event) /events/1/edit
edit action
new_event_path /events/new
new action
輸入下列指令可以看到目前的routes.rb有哪些規則
$ bin/rake routes

修改app/views/events/index.html.erb
<ul>
<% @events.each do |event| %>
  <li>
  <%= event.title %>
  <%= link_to "Show", event_path(event) %>
  <%= link_to 'Edit', edit_event_path(event) %>
  <%= button_to 'Delete', event_path(event), :method => :delete, :data => { :confirm => "Are you sure?" } %>
  </li>
<% end %>
</ul>
<%= link_to 'New Event', new_event_path %>
<%= paginate @events %>

修改app/views/events/new.html.erb
<p><%= @event.title %></p>
<table border="0">
  <tr>
    <td><%= @event.public_date %></td>
    <td><%= @event.author %></td>
  </tr>
</table>
<p><%= simple_format(@event.description) %></p>

<p><%= link_to 'Back to index', events_path %></p>

修改app/views/events/new.html.erb
<%= form_for @event, :url => events_path do |f| %>
    <%= render :partial => 'form', :locals => { :f => f } %>
    <%= f.submit "Create" %>
    <%= link_to 'Back to index', :controller => 'events', :action => 'index' %>
<% end %>

修改app/views/events/edit.html.erb
<%= form_for @event, :url => event_path(@event), :method => :patch do |f| %>
    <%= render :partial => 'form', :locals => { :f => f } %>
    <%= f.submit "Update" %>
    <%= link_to 'Back to index', :controller => 'events', :action => 'index' %>
<% end %>

修改app/controllers/events_controller.rb,要修改的部份如下,藍色是原來的code,紅色是改變後的code
  def create
    @event = Event.new(event_params)
    if @event.save
      #redirect_to :action => :index
      redirect_to events_url
    else
      render :action => :new
    end
    flash[:notice] = "event was successfully created"
  end
  
  def update
    #@event = Event.find(params[:id])
    if @event.update(event_params)
      #redirect_to :action => :show, :id => @event
      redirect_to event_url(@event)
    else
      render :action => :edit
    end
    flash[:notice] = "event was successfully updated"
  end
  
  def destroy
    #@event = Event.find(params[:id])
    @event.destroy
  
    #redirect_to :action => :index
    redirect_to events_url
    flash[:alert] = "event was successfully deleted"
  end 

文章出處還有介紹其他xml、json的運用,大家可以玩玩看,因為這邊用不到所以就不多述了。

沒有留言:

張貼留言