← Back to Upcase

Rails form_tag going to create action instead of index


(Scott Hollinshead) #1

I am putting a search field on my homepage using the form_tag helper method.

However when I do the following code

<%= form_tag(dogs_path) %>
  <%= text_field_tag "search" %>
  <%= submit_tag "Search" %>
<% end %>

Instead of it going to the index, it seems to be going to the create action instead.
The only way I managed to get around it was by doing <%= form_tag(dogs_path, method: :get) %> but that resulted in the URL containing the utf-8 and commit params it it.

I just want it so when you press search it takes you to the url www.example.com/dogs?search=test

Any help or advice would be appreciated.

UPDATE

After doing a little more digging, It seems I was half way there changing the method to GET after watching this RailsCast, the way I stop the commit=search from appearing is by doing name: nil on the submit_tag helper method.

How do I stop the utf-8 parameter showing up?


(Geoff Harcourt) #2

Hi @scott,

Can you post your routes.rb and the DogsController?


(Scott Hollinshead) #3

Hi @geoffharcourt

This is the routes.rb file.

Iwantadog::Application.routes.draw do
  root to: "homes#show", via: :get
  get "signup", to: "users#new", as: "signup"
  get "login", to: "sessions#new", as: "login"
  delete "logout", to: "sessions#destroy", as: "logout"
  resources :users, only: [:new, :create]
  resource :session, only: [:new, :create, :destroy]
  resource :dashboard, only: :show
  resource :confirmation, only: :new
  resources :dogs
end

and this is the DogsController

class DogsController < ApplicationController
  before_filter :authorize, except: [:index, :show]
  def index
    @dogs = Dog.all
  end

  def new
    @dog = Dog.new
  end

  def create
    user = User.find(session['user_id'])
    @dog = user.dogs.new(dog_params)
    if @dog.save
      redirect_to root_path
    else
      render "new"
    end
  end

  def show
    @dog = Dog.find(params[:id])
  end

  def edit
    @dog = Dog.find(params[:id])
  end

  def update
    @dog = Dog.find(params[:id])
    @dog.update_attributes(dog_params)
    if @dog.save
      flash.notice = "Advert Successfully Updated!"
      redirect_to dog_path(@dog)
    else
      flash.now.alert = "Advert has not been updated!"
      render "edit"
    end
  end

  def destroy
    @dog = Dog.find(params[:id])
    @dog.destroy
    redirect_to dogs_path
  end

  private

  def dog_params
    params.require(:dog).permit(:ad_type, :title, :body, :price, :picture)
  end
end

Hope this helps.


(Chad Pytel) #4

@scott, even though you aren’t doing anything with the utf8 parameter, Rails is. It’s to correct some issues in IE’s parameter encoding. You can find more information here http://stackoverflow.com/questions/3222013/what-is-the-snowman-param-in-rails-3-forms-for/3348524#3348524

If you really want to remove it, the solution is not not use the form_tag helper and just write your form manually.