Rails 5.1 strong parameters deprecated? - ruby-on-rails

I'm working on using form_with in Rails 5.1.3 & Ruby 2.3.0
The best documentation I've found is here
Rails Github Repo on line 533, but it's still unclear to me.
# The parameters in the forms are accessible in controllers according to
# their name nesting. So inputs named +title+ and <tt>post[title]</tt> are
# accessible as <tt>params[:title]</tt> and <tt>params[:post][:title]</tt>
# respectively.
Code:
# friendships_controller.rb
...
private
def friendship_params
params.require(:friendship).permit(:user_id, :id)
end
# Works
def destroy
Friendship.remove_friend(current_user.id, params[:id].to_i)
end
# Doesn't work
def destroy
Friendship.remove_friend(friendship_params[:user_id].to_i, friendship_params[:id].to_i)
end
# form_with
<%= form_with model: Friendship,
url: user_friendship_path(
user_id: current_user.id
id: other_user.id,
), method: :delete do |f| %>
<button class='button'></button>
<% end %>
I know the naming is a little confusing, I still haven't figured out how to get form_with to map correctly to the route I need.
friendships#destroy located at path
/users/:user_id/friendships/:id(.:format)
resources :users do
resources :friendships
end
Error Message
Started DELETE "/users/1/friendships/8" for 127.0.0.1 at 2018-01-02 03:21:40 +0700
Processing by FriendshipsController#destroy as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"fWnYwpNDItctgg3q/TYIXy5VRO55nwQRINCCykMsDPAFBfwJKjMZ1dneNbg 5yFNHaQP+lXR4ViTje6mK+dCmVg==", "user_id"=>"1", "id"=>"8"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
(0.2ms) BEGIN
(0.1ms) COMMIT
Friendship Load (1.0ms) SELECT "friendships".* FROM "friendships" WHERE "friendships"."friend_id" = $1 AND "friendships"."user_id" = $2 ORDER BY "friendships"."id" ASC LIMIT $3 [["friend_id", 1], ["user_id", 8], ["LIMIT", 1]]
SQL (1.2ms) DELETE FROM "friendships" WHERE "friendships"."id" = $1 [["id", 499]]
Friendship Load (0.5ms) SELECT "friendships".* FROM "friendships" WHERE "friendships"."friend_id" = $1 AND "friendships"."user_id" = $2 ORDER BY "friendships"."id" ASC LIMIT $3 [["friend_id", 8], ["user_id", 1], ["LIMIT", 1]]
SQL (0.9ms) DELETE FROM "friendships" WHERE "friendships"."id" = $1 [["id", 498]]
Completed 400 Bad Request in 13ms (ActiveRecord: 4.2ms)
ActionController::ParameterMissing (param is missing or the value is empty: friendship):
app/controllers/friendships_controller.rb:40:in `friendship_params'
app/controllers/friendships_controller.rb:22:in `destroy'
Maybe I shouldn't say it doesn't work, the behavior is how I expect with or without the friendship_params. However, the server logs returning a 400 Bad Request is a red flag to me.
Thanks for any suggestions in advance~!

The route is a nested resource, so you should provide two arguments to the path. you also need to provide the scope to give it the "friendship" key in the params.
<%= form_with scope: :friendship, url: user_friendship_path(current_user, other_user), method: :delete do |f| %>
<button class='button'></button>
<% end %>

This code is little bit confusing, I suggesting the way for simple like change your route like below
resources :users do
resources :friendships
end
Change to
resources :users
resources :friendships
and on the view
<%= link_to "Remove Friend", friendship_path(friend_id), method: :delete, data: {confirm: "Are you sure"}, class: "btn btn-xs btn-danger" %>
and finally the controller
def destroy
#friendship = current_user.friendships.where(friend_id: params[:id]).first
#friendship.destroy
flash[:notice] = "Friend was removed"
redirect_to(my_friends_path)
end
Hope to help

The answer was that the arguments to the form_with don't pass the actually parameters to the key Friendship, we have to pass them manually within the body of the form.
<%= form_with model: Friendship, url:
user_friendship_path(
current_user, other_user
), method: :delete do |f| %>
<%= f.hidden_field :id, value: other_user.id %>
<button class='button'></button>
<% end %>

Related

Confirm Rails Devise user with checkbox

While administering users, I'd like the administrator to be able to confirm a user's account using a checkbox to trigger the user's devise user.confirm method.
I initially thought I'd be able to use attr_accessor to setup a variable called confirm_now to be used as a boolean on the user form, then in the controller update action (or by before/after action callback) evaluate the boolean and confirm the user accordingly.
I'm still not quite sure if I need methods in the model to set and read the attr_accessor variable, I'm still getting my head around that...or perhaps I'm over-complicating this and should call the user.confirm method when clicking save (is this bad practice? - I'm hesitant to add this field into the user_params).
Model:
class User < ApplicationRecord
attr_accessor :confirm_now
...
Controller:
class UsersController < ApplicationController
...
def update
if params[:user][:password].blank?
params[:user].delete(:password)
params[:user].delete(:password_confirmation)
end
if !#user.confirmed? && #user.confirm_now
#user.confirm
end
...
private
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :account_active, :confirm_now)
end
Form snippet (this evaluates and works as expected):
<% if !#user.confirmed? %>
<%= f.input :confirm_now, label: 'Confirm User', as: :boolean, checked_value: true, unchecked_value: false %>
<% end %>
Rails Log (the attr_accessor is set when checked on the form):
Processing by UsersController#update as HTML
Parameters: {"authenticity_token"=>"...", "user"=>{"first_name"=>"gg", "last_name"=>"gg", "email"=>"gg#gg.com", "account_active"=>"1", "confirm_now"=>"true", "password"=>"[FILTERED]"}, "commit"=>"Save", "id"=>"45"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."first_name" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."first_name" ASC LIMIT $2 [["id", 45], ["LIMIT", 1]]
CACHE User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."first_name" ASC LIMIT $2 [["id", 45], ["LIMIT", 1]]
Redirected to http://localhost:3000/users
Completed 302 Found in 6ms (ActiveRecord: 0.6ms | Allocations: 2665)
Thanks in advance!
To simplify I would make it a button, and pass the confirmed_at field directly.
Parameter whitelisting:
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :account_active, :confirmed_at)
end
Form:
<%=
if #user.confirmed?
link_to 'Unconfirm user',
user_path(#user, { user: { confirmed_at: nil } }),
method: :patch
else
link_to 'Confirm user',
user_path(#user, { user: { confirmed_at: Time.current } }),
method: :patch
end
%>
Please adjust the paths/method types according to your routes.

Can't purge active storage attachments

I have a model called Resource configured with:
class Resource < ActiveRecord::Base
has_many_attached :assets
end
I created an action in my resources_controller.rb as follows:
def delete_asset_attachment
#asset = ActiveStorage::Attachment.find_by(params[:id])
logger.debug "The value of #asset is #{#asset}"
#asset.purge
redirect_to #resource
end
I have a form that shows the resource and loops through the attached assets. Below is the snippet of code doing the loop through the assets:
<% #resource.assets.each do |asset| %>
<%= link_to 'Remove Attachment', delete_asset_attachment_resource_url(#resource, asset.id), method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
The /resources page properly shows the resource along with the attached assets. However, when I try to click the link to delete one of the assets, I receive an error: "undefined method `purge' for nil:NilClass". However, in console I see the attachment exists.
Here is the output from the server console:
Started DELETE "/resources/10/delete_asset_attachment.18" for ::1 at 2019-03-09 17:27:28 -0500
Processing by ResourcesController#delete_asset_attachment as
Parameters: {"authenticity_token"=>"EFZO5V9Bii3dId0I6hn5DajFR5WJYZBc8qPAAi5ppQOFW3cws5I4FjyVP9IlvA+2a2kKUJhobnqd8atG4L3k+g==", "id"=>"10"}
Resource Load (0.1ms) SELECT "resources".* FROM "resources" WHERE "resources"."id" = ? LIMIT ? [["id", 10], ["LIMIT", 1]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]]
ActiveStorage::Attachment Load (0.1ms) SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE (10) LIMIT ? [["LIMIT", 1]]
The value of #asset is #<ActiveStorage::Attachment:0x00007f8d7bd4df68>
ActiveStorage::Blob Load (0.2ms) SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = ? LIMIT ? [["id", 27], ["LIMIT", 1]]
Completed 500 Internal Server Error in 5ms (ActiveRecord: 0.6ms)
NoMethodError - undefined method `purge' for nil:NilClass:
::1 - - [09/Mar/2019:17:27:28 EST] "POST /resources/10/delete_asset_attachment.18 HTTP/1.1" 500 76939
http://localhost:3000/resources/10/edit -> /resources/10/delete_asset_attachment.18
Started POST "/__better_errors/70da0e976a425fce/variables" for ::1 at 2019-03-09 17:27:28 -0500
ActiveStorage::Blob Load (0.2ms) SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = ? LIMIT ? [["id", 27], ["LIMIT", 11]]
::1 - - [09/Mar/2019:17:27:28 EST] "POST /__better_errors/70da0e976a425fce/variables HTTP/1.1" 200 36499
http://localhost:3000/resources/10/delete_asset_attachment.18 -> /__better_errors/70da0e976a425fce/variables
I've searched for solutions everywhere. The couple that exist on stackoverflow didn't address my issue. There is an incredible lack of specific details and examples in the Rails guide or anywhere else on the web for specifically handling deleting attachments. Would appreciate any help.
UPDATE: Here are my routes.rb:
resources :resources do
get 'listing', :on => :collection
put :sort, on: :collection
member do
delete :delete_asset_attachment
end
end
UPDATE 2: rails routes output
resources GET /resources(.:format) resources#index
POST /resources(.:format) resources#create
new_resource GET /resources/new(.:format) resources#new
edit_resource GET /resources/:id/edit(.:format) resources#edit
resource GET /resources/:id(.:format) resources#show
PATCH /resources/:id(.:format) resources#update
PUT /resources/:id(.:format) resources#update
DELETE /resources/:id(.:format) resources#destroy
I've been able to make this work. Ahhhh. The rush, after hours of frustration.
Piecing things together after reading this article
Deleting ActiveStorage Attachments From the Controller, 3 Ways
I changed my controller code to be this:
def delete_asset_attachment
#resource.assets.find_by(params[:attachment_id]).purge
redirect_to #resource
end
and my form to be this:
<% #resource.assets.each do |asset| %>
<%= asset.filename %>
<%= link_to 'Remove Attachment', delete_asset_attachment_resource_url(#resource, asset.id), method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
I believe the issue was that the line in my old code:
#asset = ActiveStorage::Attachment.find_by(params[:id])
...was only passing the #resource id and the attachment was not being found. The key was changing this line:
#resource.assets.find_by(params[:attachment_id]).purge
...which more properly points to the correct resource and then the specific asset (attachment) to be purged.
Fix the syntax of find_by and use safe ampersand, instead
#asset = ActiveStorage::Attachment.find_by(params[:id])
#asset.purge
try:
#asset = ActiveStorage::Attachment.find_by(id: params[:id])
#asset&.purge

How to pass data from view that came from an external API to a controller?

So I want to pass a data from a view that was rendered from an external api to a controller to be able to save the ID to a model/database table.
This is my view:
<h1>Heroes</h1>
<% #response.each do |hero| %>
<div class = "hero_wrap">
<div class = "img">
<img src="https://api.opendota.com<%= hero["img"]%>", id ="hero_img"/>
</div>
<div class = "fave_container">
<%= link_to(image_tag('fave.png', class: "fave_img"), new_hero_path) %>
<%= hero["id"]%>
</div>
<div class = "hero_name">
<%= hero["localized_name"] %>
</div>
</div>
<% end %>
My controller:
# heroes_controller
class HeroesController < ApplicationController
def index
#response = HTTParty.get("https://api.opendota.com/api/heroStats")
end
def create
#hero= Hero.new(params[:id])
#hero.save
redirect_to #hero
end
end
Routes:
Rails.application.routes.draw do
get '/signup', to: 'users#new'
get 'pages/home'
resources :pro_players
devise_for :users
resources :heroes
resources :users
root 'pages#home'
end
My hero model doesn't contain anything yet, I just want to pick the hero id and save it to my database.
this is my web app
server log upon clicking the star icon with link:
Started GET "/heros?custom_hero_id=1&method=post" for 127.0.0.1 at
2018-10-15 09:20:53 +0800
Processing by HerosController#index as HTML
Parameters: {"custom_hero_id"=>"1", "method"=>"post"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳/home/don/.asdf/installs/ruby/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-
5.2.1/lib/active_record/log_subscriber.rb:98
Rendering heros/index.html.erb within layouts/application
Rendered heros/index.html.erb within layouts/application (42.2ms)
Rendered layouts/_header.html.erb (1.1ms)
Rendered layouts/_footer.html.erb (0.4ms)
Completed 200 OK in 770ms (Views: 83.3ms | ActiveRecord: 0.7ms)
Updated log:
Started POST "/heros?custom_hero_id=21" for 127.0.0.1 at 2018-10-15 10:13:17 +0800
Processing by HerosController#create as HTML
Parameters: {"authenticity_token"=>"PHDEXdDmPhPX+VdloU2y6yONY5HN5wI2lIfOaSbSKj9+RvTO5Ua3QPuTcreLZtGNDFPaSOXhDVyve6J69+1CQQ==", "custom_hero_id"=>"21"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳/home/don/.asdf/installs/ruby/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
(0.2ms) BEGIN
↳ app/controllers/heros_controller.rb:9
Hero Create (0.4ms) INSERT INTO "heros" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", "2018-10-15 02:13:17.032248"], ["updated_at", "2018-10-15 02:13:17.032248"]]
↳ app/controllers/heros_controller.rb:9
(42.3ms) COMMIT
↳ app/controllers/heros_controller.rb:9
Redirected to http://localhost:3000/heros/10
Completed 302 Found in 59ms (ActiveRecord: 46.9ms)
Started GET "/heros/10" for 127.0.0.1 at 2018-10-15 10:13:17 +0800
AbstractController::ActionNotFound (The action 'show' could not be found for HerosController):
The :id attribute is by default a auto-increment attribute of datatype integer which sets its value under the hood whenever a new instance of the model is created. There are several ways to override the its behavior or setting its value explicitly, but considering that you are fairly new to the technology I don't recommend those for you. Instead I recommend a simpler solution of using another attribute to store hero["id"]
Steps:
1) Generate a migration to create a new column(say custom_hero_id) in the heroes table
rails g migration add_custom_hero_id_to_heroes custom_hero_id:integer
and do rake db:migrate
2) Change
<%= link_to(image_tag('fave.png', class: "fave_img"), new_hero_path) %>
to
<%= link_to(image_tag('fave.png', class: "fave_img"), heroes_path(custom_hero_id: hero["id"]), method: :post) %>
3) Finally change your create action to below
def create
#hero= Hero.create(custom_hero_id: params[:custom_hero_id])
redirect_to #hero
end
Update:
Due to unknown reason, custom_hero_id isn't saving to the DB. Probably due to forbidden attributes error. Try changing it to
def create
#hero = Hero.new(hero_params)
if #hero.save
redirect_to #hero
end
end
private
def hero_params
params.permit(:custom_hero_id)
end
Do you want to store the hero id or it's name ?
I would advise to create a method in your heroe model. Something like
// heroe.rb
def save_api_heroes_to_db(response)
response.each do |hero|
unless hero[:localized_name].exists?
hero.create(id: hero[:id], name: hero[:localized_name], image: hero[:img])
end
end
end
This method will save the heroe id, name and image in your database (unless it already exists).
You just have to call it in your index method, in your heroe controller.
Hope that helps.

Rails form submitting but not creating

Hey guys not sure what's going on here. I have Movies and Critics on my app. I've set up an assocation between those and Reviews. I'm trying to set up the controller and form to create and destroy Reviews. In the rails console I can create reviews that belong to both just fine and I have tested my controller (may be incorrect though) and it seems to be working, so I think the problem is in my form. Thanks in advance guys. Here's the codeand server logs:
class ReviewsController < ApplicationController
def create
#movie = Movie.find(params[:movie_id])
current_critic.reviews.create(content: params[:content], movie_id: #movie.id)
redirect_to #movie
end
def destroy
#movie = Movie.find(params[:movie_id])
#review = current_critic.reviews.find_by(movie_id: #movie.id)
#review.delete
redirect_to #movie
end
end
form:
<div class="form">
<h1 class="smaller">Write a Review</h1>
<%= form_for(current_critic.reviews.new) do |r| %>
<%= hidden_field_tag :movie_id, #movie.id %>
<ul>
<li>
<%= r.text_area :content, placeholder: "Write your review...", size: "50x10" %>
</li>
<li>
<%= r.submit "Submit Review" %>
</li>
</ul>
<% end %>
</div>
server log after submitting form:
Started POST "/reviews" for 99.39.164.184 at 2015-12-04 20:34:59 +0000
Processing by ReviewsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"d16BVZxzqZY5bQrw9xr2VlWbWjh0Dc7bL6t4OgKQPk1RXWt40acMjtkjXG9DUBBfnA7K06iJDwQzd5YJ0D6c4Q==", "movie_id"=>"2", "review"=>{"content"=>"One last try at writing and submitting a review before I head out"}, "commit"=>"Submit Review"}
Movie Load (2.1ms) SELECT "movies".* FROM "movies" WHERE "movies"."id" = ? LIMIT 1 [["id", 2]]
Critic Load (0.2ms) SELECT "critics".* FROM "critics" WHERE "critics"."id" = ? LIMIT 1 [["id", 1]]
(5.3ms) begin transaction
(0.9ms) commit transaction
Redirected to https://everyones-a-critic-caedbudris.c9users.io/movies/2
Completed 302 Found in 574ms (ActiveRecord: 18.1ms)
EDIT: I implemented strong paramaters for create so the controller is now
def create
#movie = Movie.find(params[:movie_id])
current_critic.reviews.create(review_params)
redirect_to #movie
end
private
def review_params
params.require(:review).permit(:content, :movie_id)
end
And it is now inserting into reviews, but for some reason it's not getting the movie_id passed by the hidden_field_tag. Why is this?
Started POST "/reviews" for 99.39.164.184 at 2015-12-05 21:31:07 +0000
Processing by ReviewsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"OlBIfneoWTvBtIeISTF9ubo9jj06oVyfDd6rswxe7xO+JyGXRvFV4TLD+3xKhBZHRF+eRJAawKUabU7KrLpZow==", "movie_id"=>"2", "review"=>{"content"=>"review review review review review"}, "commit"=>"Submit Review"}
Movie Load (0.3ms) SELECT "movies".* FROM "movies" WHERE "movies"."id" = ? LIMIT 1 [["id", 2]]
Critic Load (0.3ms) SELECT "critics".* FROM "critics" WHERE "critics"."id" = ? LIMIT 1 [["id", 1]]
(0.1ms) begin transaction
SQL (6.4ms) INSERT INTO "reviews" ("content", "critic_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["content", "review review review review review"], ["critic_id", 1], ["created_at", "2015-12-05 21:31:08.185722"], ["updated_at", "2015-12-05 21:31:08.185722"]]
(10.3ms) commit transaction
Redirected to https://everyones-a-critic-caedbudris.c9users.io/movies/2
Completed 302 Found in 157ms (ActiveRecord: 25.6ms)
You should whitelist your parameters, by default rails won't accept any parameters to avoid mass assignment. Proper way is to define a protected block at the bottom of your controller. Like this,
protected
def rating_params
params.require(:rating).permit(:content)
end
And you can use it like
current_critic.reviews.create(rating_params)

Params passed into URL Ruby on Rails

I'm having some issue with my form_tag search functionality is not redirecting me properly to a place where I can see the results of my search.
It was working fine yesterday, Once the submit button of the search is clicked, a get request to the pets controller search method is fired and then I was redirected to the results.html.erb page where the results are displayed.
The problem is that now when I submit the search, it's just refreshing the page (index.html.erb) and my params are passed to the URL but none of the "pets" i searched for are displayed.
http://localhost:3000/?utf8=%E2%9C%93&authenticity_token=iDXugIhTyjknCMpPh2P5x7voNMSQ3Y7Aa1HIZPA7xqZ9Oj4CAuVc5eJPqfE1CLwxXAsCebgPuNWqpOk381TlvQ%3D%3D&pets%5Bzip_code%5D=10019&pets%5Bspecies%5D=Cat&pets%5Bbreed%5D=&pets%5Bage%5D=&pets%5Bsex%5D=&pets%5Bsize%5D=&commit=Find+Pets%21
Before it was just redirecting me the results page localhost:3000/results
Here is my pets controller
class PetsController < ApplicationController
def index #index page will render search form
#pet = Pet.new
#send form data in params to create
end
def search
#pets = Pet.where(clean_params)
render :results
end
private
def thinned_params
params["pets"].delete_if {|k, v| v.empty?}
end
def clean_params
thinned_params.permit(:species, :zip_code, :sex, :size, :breed, :age)
end
end
My form_tag in welcome#index:
<form class="form-horizontal">
<%= form_tag :controller => 'pets', :action => 'search', :method => 'get' do %>
<%= label_tag('pets[zip_code]', "Zipcode") %>
<%= text_field_tag('pets[zip_code]') %>
<%= label_tag('pets[species]', "Type") %>
<%= select_tag('pets[species]', options_for_select([["Dog","Dog"],["Cat","Cat"],["Rabbit", "Rabbit"], ["Small & Furry","Smallfurry"],["Horse", "Horse"],["Pig", "Pig"],["Reptile", "Reptile"],["Bird", "Bird"],["Barnyard", "Barnyard"]])) %>
<%= label_tag('pets[breed]', "Breed") %>
<%= text_field_tag('pets[breed]', nil, class: 'typeahead') %>
<%= label_tag('pets[age]', "Age") %>
<%= select_tag('pets[age]', options_for_select([["None",""],["Baby","Baby"],["Young","Young"],["Adult", "Adult"], ["Senior","Senior"]])) %>
<%= label_tag('pets[sex]', "Gender") %>
<%= select_tag('pets[sex]', options_for_select([["None",""],["Male","M"],["Female","F"]])) %>
<%= label_tag('pets[size]', "Size") %>
<%= select_tag('pets[size]', options_for_select([["None",""],["Small","S"],["Medium","M"], ["Large", "L"], ["Xtra Large", "XL"]])) %>
<%= submit_tag "Find Pets!" %>
<%end%>
</form>
And finally...my routes.rb
Rails.application.routes.draw do
devise_for :users
resources :users
# resources :pets
root 'welcome#index'
get '/pets' => 'pets#index'
post '/pets/search' => 'pets#search'
resources :favorite_pets
get '/my_pets' => 'users#my_pets'
end
So my question is why is my params passed to the URL when it should just hit the search method in the pets controller and redirect me to the results page displaying the info?
Second question, obviously, what can I do to fix this problem?
UPDATE
here is the output of my console when the "search" button is clicked.
Started GET "/?utf8=%E2%9C%93&authenticity_token=NgVe%2Fe5i6sn8ijRmgcvOezp62KlymrNRWPJfFNOVJ54ChWpZf8JYTm%2Fk%2FeHdDsvcgzdBYe%2BjUX5jiz2JeALEpQ%3D%3D&pets%5Bzip_code%5D=10019&pets%5Bspecies%5D=Cat&pets%5Bbreed%5D=&pets%5Bage%5D=&pets%5Bsex%5D=&pets%5Bsize%5D=&commit=Find+Pets%21" for ::1 at 2015-03-15 15:54:34 -0400
Processing by WelcomeController#index as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"NgVe/e5i6sn8ijRmgcvOezp62KlymrNRWPJfFNOVJ54ChWpZf8JYTm/k/eHdDsvcgzdBYe+jUX5jiz2JeALEpQ==", "pets"=>{"zip_code"=>"10019", "species"=>"Cat", "breed"=>"", "age"=>"", "sex"=>"", "size"=>""}, "commit"=>"Find Pets!"}
Pet Load (0.7ms) SELECT "pets".* FROM "pets"
CACHE (0.0ms) SELECT "pets".* FROM "pets"
CACHE (0.0ms) SELECT "pets".* FROM "pets"
CACHE (0.0ms) SELECT "pets".* FROM "pets"
Breed Load (0.2ms) SELECT "breeds".* FROM "breeds" INNER JOIN "pet_breeds" ON "breeds"."id" = "pet_breeds"."breed_id" WHERE "pet_breeds"."pet_id" = ? [["pet_id", 71]]
Shelter Load (0.1ms) SELECT "shelters".* FROM "shelters" WHERE "shelters"."id" = ? LIMIT 1 [["id", 26]]
Breed Load (0.3ms) SELECT "breeds".* FROM "breeds" INNER JOIN "pet_breeds" ON "breeds"."id" = "pet_breeds"."breed_id" WHERE "pet_breeds"."pet_id" = ? [["pet_id", 73]]
CACHE (0.0ms) SELECT "shelters".* FROM "shelters" WHERE "shelters"."id" = ? LIMIT 1 [["id", "26"]]
Breed Load (0.1ms) SELECT "breeds".* FROM "breeds" INNER JOIN "pet_breeds" ON "breeds"."id" = "pet_breeds"."breed_id" WHERE "pet_breeds"."pet_id" = ? [["pet_id", 41]]
Shelter Load (0.1ms) SELECT "shelters".* FROM "shelters" WHERE "shelters"."id" = ? LIMIT 1 [["id", 16]]
Breed Load (0.1ms) SELECT "breeds".* FROM "breeds" INNER JOIN "pet_breeds" ON "breeds"."id" = "pet_breeds"."breed_id" WHERE "pet_breeds"."pet_id" = ? [["pet_id", 9]]
Shelter Load (0.1ms) SELECT "shelters".* FROM "shelters" WHERE "shelters"."id" = ? LIMIT 1 [["id", 5]]
Rendered welcome/index.html.erb within layouts/application (20.9ms)
Completed 200 OK in 127ms (Views: 125.2ms | ActiveRecord: 1.6ms)
Rake Routes
https://slack-files.com/files-pub/T02MD9XTF-F041PKBE2-532b801cb1/-.txt
According to your routes file, the search action only accepts POST (not GET):
post '/pets/search' => 'pets#search'
That seems appropriate, so just change your form action to use the POST method:
form_tag :controller => 'pets', :action => 'search', :method => :post
Your route is POST, but that makes no sense, are you trying to update or replace pets? No, you getting a list of pets. You are already calling a GET request in your form, so you can leave that, and change
post '/pets/search' => 'pets#search' to get '/pets/search' => 'pets#search'
More information on get and post.

Resources