stergosz
stergosz

Reputation: 5860

ruby on rails use "create" method in controller as GET not working

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

when i go to http://localhost:3000/friendships?friend_id=1 i get

Unknown action

The action 'index' could not be found for FriendshipsController

I followed this tutorial : http://railscasts.com/episodes/163-self-referential-association

Upvotes: 2

Views: 2214

Answers (2)

Fareesh Vijayarangam
Fareesh Vijayarangam

Reputation: 5052

As mentioned in the other post, this is probably caused due to the fact that the default scaffolding for rails configures POST requests to work as create. To fix this, you can try something like this, although I'm not sure it will work.

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

The downside is that a GET request to /friendships will not give you the index action, as is the default case.

Maybe you can fix this with something like this:

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

Upvotes: 0

Kai Mattern
Kai Mattern

Reputation: 3085

You probably configured the create as a POST not a GET.

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

This is also the case if you used scaffolding to create a skeleton of your controller. You could change this in the routes configuration. But be aware, that creating stuff via GET is no longer seen as completely conform to the REST paradigm.

Upvotes: 3

Related Questions