我如何在rails中进行POST?

时间:2013-04-02 16:58:05

标签: ruby-on-rails ruby-on-rails-3 rest ruby-on-rails-3.1 ruby-on-rails-3.2

以下是我的控制器代码和视图代码。该视图显示了一个游戏列表,我想在同一视图中将游戏添加到现有表中。我在邮寄程序方面遇到了一些问题。任何建议或任何人都可以指出我可能做错了什么?

class GamesController < ApplicationController

  # GET /games
  def index
    @games = []
    client = Games::Client.new
    @games =client.get_games
    if @games.blank?
      render_404
    end  
    if params[:name]
      client.create_games params[:name] 
    end
  end
end


%nav.navigation-bar.clearfix{:role => "navigation"}
  %h3.reader-details Game tools
  %a.home{:href => root_path, :role => "link", :title => "Home"}Home
%body
  %section.form
    %form.standard{:action => "/games", :method => "post"}
      %input{type: 'text', name: 'name', class: 'text'}
      %input.primary-action{type: 'submit', value: 'Add', class: 'button'}
  .content
    - if @games.present?
      %table.games
        %thead
          %tr
            %th type
            %th id            
        %tbody
          - @games.each do |game|
            %tr
              %td= game['type']
              %td= game['id']

         %a= link_to "Back", root_path          

1 个答案:

答案 0 :(得分:0)

您没有定义create操作。当您为资源创建RESTful路由时,/games的POST不会查找index操作,而是查找create操作。

支持您的资源是了解Rails希望您做什么的好方法。

rails g scaffold game name:string

这将创建您的RESTful路由,它将在您的控制器中创建与它们对应的操作。请注意,您可能想要在尝试脚手架之前废弃您所拥有的东西,否则脚手架可能无法创建所需的一切。如果您想在以后将其粘贴回来,请将视图代码保存到临时文件中。

这或多或少我会如何去做:

# View
= form_for Game.new do |f|
  = f.text_field :name
  = f.submit 'Add'

# Controller
  def create
    if Game.create(params[:game])
      redirect_to :action => 'index'
    else
      flash[:notice] = "There was a problem creating your new game"
      render :action => 'index'
    end
  end

# Routes
  resources :games