【问题标题】:ruby on rails use "create" method in controller as GET not workingruby on rails 在控制器中使用“create”方法,因为 GET 不起作用
【发布时间】:2012-09-14 21:20:32
【问题描述】:

friendships_controller.rb

class FriendshipsController < ApplicationController

  # POST /friendships
  # POST /friendships.json
  def create

    #@friendship = Friendship.new(params[:friendship])
    @friendship = current_user.friendships.build(:friend_id => params[:friend_id])

    respond_to do |format|
      if @friendship.save
        format.html { redirect_to user_profile(current_user.username), notice: 'Friendship was successfully created.' }
        format.json { render json: @friendship, status: :created, location: @friendship }
      else
        format.html { redirect_to user_profile(current_user.username), notice: 'Friendship was not created.' }
        format.json { render json: @friendship.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /friendships/1
  # DELETE /friendships/1.json
  def destroy
    @friendship = Friendship.find(params[:id])
    @friendship.destroy

    respond_to do |format|
      format.html { redirect_to friendships_url }
      format.json { head :no_content }
    end
  end
end

当我去http://localhost:3000/friendships?friend_id=1 我得到

Unknown action

The action 'index' could not be found for FriendshipsController

我遵循了这个教程:http://railscasts.com/episodes/163-self-referential-association

【问题讨论】:

    标签: ruby-on-rails model-view-controller


    【解决方案1】:

    您可能将创建配置为 POST 而不是 GET。

      # POST /friendships
      # POST /friendships.json
      def create
    

    如果您使用脚手架创建控制器的骨架,情况也是如此。您可以在路由配置中更改此设置。但请注意,通过 GET 创建内容不再被视为完全符合 REST 范式。

    【讨论】:

    • 我将通过 ajax 处理这些友谊请求,但由于我刚开始,我以为我会按照上面列出的教程进行操作,但后来我遇到了这个问题......还查看了教程源代码而且我在将创建的 POST 更改为 GET 的路线上找不到任何奇怪的东西......
    • 这个页面上有一些关于路由的内容:guides.rubyonrails.org/routing.html - 标准条目可能类似于:resources :friendships - 但这就像创建标准操作的宏。在这种情况下,标准意味着 POST 映射到创建。
    【解决方案2】:

    正如在另一篇文章中提到的,这可能是由于 Rails 的默认脚手架将 POST 请求配置为创建。要解决此问题,您可以尝试类似的方法,但我不确定它是否会起作用。

       match "/friendships" => "friendships#create", :via => [:get]
       get   "/friendships" => "friendships#create"
    

    缺点是GET/friendships 的请求不会像默认情况那样为您提供index 操作。

    也许你可以用这样的东西来解决这个问题:

    match "/all_friendships", :to => "friendships#index", :via => :get, :as => :friendships
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多