Rails ajax更新,没有路由匹配[POST]

时间:2014-01-19 00:49:05

标签: ruby-on-rails ajax forms

我有一个模型Game,Ownedsq和User的应用程序,我正在尝试更新游戏中的方块:user_id。我现在已经尝试了好几个小时,我相信模型关系是正确的,我只是缺少一些小的东西,所以我感谢任何帮助。

单击特定方块上的更新ownsq按钮会给出错误:没有路由匹配[POST]“/ games / 2”,尽管我的routes.rb中有资源:ownedsqs。我的想法可能是它没有传递正确的ownsq id,因为我之前从未使用过each_slice嵌套,所以也许我搞砸了。

游戏/ show.html.erb

<div class="squareBoard">
    <% @ownedsqs.each_slice(10) do |slice| %>
        <div class='row'>
            <% slice.each do |s| %>
                <%= div_for s, class: 'sq' do %>
                    <%= s.boardposition %>
                    <%= button_to ownedsq_path(s.id), method: :put, type: 'JSON', data: {confirm: "Are you sure?"}, remote: :true %>
                <% end %>
            <% end %>
        </div>
    <% end %>
</div>

games_controller.rb

def show
    require 'enumerator'
    @user = current_user
    @game = Game.find(params[:id])
    @ownedsqs = Ownedsq.all
end

ownedsqs_controller.rb

def update
    @ownedsq = Ownedsq.find(params[:ownedsq_id])

    respond_to do |format|
        format.js
        if @ownedsq.update_attributes(user_id: current_user.id)
            format.html {redirect_to game_path}
            format.json {head :no_content, status: :200}
        else
            format.html {redirect_to :back}
            format.json {status: :500 }
        end  
    end 
end

game.rb

has_many :ownedsqs
has_and_belongs_to_many :users

accepts_nested_attributes_for :ownedsqs

def after_create
    1.upto(100) do |i|
      Ownedsq.create("boardposition" => i)
    end
end

ownedsq.rb

belongs_to :user
belongs_to :game

user.rb

has_and_belongs_to_many :games
has_many :ownedsqs

accepts_nested_attributes_for :ownedsqs

的routes.rb

 resources :games, :users, :ownedsqs

4 个答案:

答案 0 :(得分:0)

你没有设置正确的路线。

将此行添加到config/routes.rb

resources :games

我希望它有所帮助。

答案 1 :(得分:0)

两个观察结果:

  1. 如果您在 GamesController#show 操作中使用params[:id],则 OwnedsqsController中的行format.html {redirect_to game_path}不应更新行动更像是:

    format.html { redirect_to game_path(@ownedsq.game) }
    
  2. 您确定数据库中是否存在ID为2的游戏?否则,@game = Game.find(params[:id])行会因ActiveRecord::RecordNotFound而失败,这可能会触发您的路线问题。

  3. 希望这有帮助。

答案 2 :(得分:0)

基本上你调用update方法和update方法适用于你用POST请求类型调用它的PUT请求类型

答案 3 :(得分:0)

如果您输入rake routes,它会显示所有可用的路线, resources :games将使用PUT, GET, DELETE方法创建路由,您将没有与POST匹配的路由。你的ajax电话会发帖子请求。

为此,您可以创建一个像这样的自定义路线

match '/games/:id', :to => 'games#create', :via => [:post]

或者如果您想要更新操作,请执行此操作

match '/games/:id', :to => 'games#update', :via => [:post]