RubyOnRails演習 (2)

2013-04-24T00:00:00+00:00 Ruby Rails

前回のあかん事が発覚。まぁほとんどあかんと思うんだけど

前回のだと、config/routes.rbの最後に定義されている

match ":controller(/:action(/:id))(.:format)"

なやつを使ってて、今時なRailsではこれあかん系らしい。resourcesを使いましょうという事らしい。という事で直して見ることに。という事でconfig/routes.rbに

resources :entry

な感じで定義。URL的には

  • /entry -> method:index (HTTP: GET)
  • /entry -> method:create (HTTP: POST?)
  • /entry/(:id) -> method:show (HTTP: GET)
  • /entry/(:id) -> method:update (HTTP: PUT)
  • /entdy/(:id) -> method:destroy (HTTP: DELETE)

な感じでRestfulな方式なURL方式が生成される模様。でこれに沿ってコントローラーとビューをいじる

app/controllers/entry_controller.rb

class EntryController < ApplicationController

  def index
    @entries = Entry.all(:limit => 10)
  end

  def create
    entry = Entry.new(params[:entry])

    if entry.valid?
      entry.save()

      redirect_to :action => :index
    else
      @errors = entry.errors

      render :new
    end
  end

  def edit
    @entry = Entry.find_by_id(params[:id])

    if @entry.nil?
      render_error_404 # application_controllerに定義
    end
  end

  def update
    entry = Entry.find_by_id(params[:id])
    entry.title = params[:entry][:title]
    entry.content = params[:entry][:content]
    entry.category = params[:entry][:category]
    entry.save

    redirect_to :action => :index
  end

  def destroy
    entry = Entry.find_by_id(params[:id])

    unless entry.nil?
      entry.destroy
    end

    redirect_to :action => :index
  end
end

メソッド名とかが前回とちょっと異なる程度。あとちょっとだけバリデーションなコードが含まれてるけど、今回もノータッチで

app/views/entry/index.erb

<div id="container">
  <div id="menu">
    <a href="/entry/new">New</a>
  </div>

  <% @entries.each do |entry| %>
  <div class="entry">
    <ul>
      <li>
        <%= link_to "Edit", :action => "edit", :id => entry.id %>
      </li>
      <li>
        <%= link_to "Delete", entry, :action => "destroy", :method => :delete, :confirm => "OK?" %>
      </li>
    </ul>
    <% entry.category.each do |category| %>[<%= category.name %>]<% end %>
    <%= entry.title %>
  </div>
  <% end %>
</div>

destroyな処理をするにはDELETEメソッドでリクエストされるようにしないといけないのだけど、普通にlink_toをするとGETメソッドな方式になる模様なので:method => :deleteにしてDELETEメソッドで処理するようにJavaScriptでごにょごにょされるようになるらしい。

<a href="/entry/[id]" data-confirm="OK?" data-method="delete">Delete</a>

みたいな感じで出力されていれば処理出来る模様。で昨日はまったのが、上記のように出力されずに?method=deleteみたいにクエリーについちゃうのはlink_toの引数が「ラベル, モデル?, オプション」な形式で指定しないとその方式で出力されない模様

でnewとeditに関してはHTTPメソッドが異なる訳なのだけど、

form_for(@entry, :method => :put)

な感じでやっても

のmethodはpostになってるけど、

<input type="hidden" name="_method" value="put" />

なるのが埋め込まれている。これがX-Method-Override的な扱いされるのかどうかは不明

とりまぁこんな所かなー。とにかく旧式なルーティング方式は採用するべきでは無いっていう所で

RubyOnRails演習 (3) RubyOnRails演習 (1)