Edit form wrongly being submitted as GET - Rails - ruby-on-rails

I'm trying to edit using a form <%= form_for #agent, :action => 'agents/update', :method => :put do |f| %> but when I click on Save Changes the form is submitted as a GET request instead of a PUT to the update action.
I have resources :agents in my routes.rb file.
In agents_controller.rb the show and update actions are:
def show
#agent = Agent.find(params[:id])
#subscription = #agent.subscription
end
def edit
#agent = Agent.find(params[:id])
#subscription = #agent.subscription
end
def update
#agent = Agent.find(params[:id])
#subscription = #agent.subscription
#agent.update_attributes(:agent)
end
It's pretty depressing when you can't get a standard edit form working, any help appreciated.
EDIT
agents/edit.html.erb
<%= form_for #agent do |f| %>
<ul>
<% for message in #agent.errors.full_messages %>
<li><%= message %></li>
<% end %>
</ul>
<div class="control-group">
<label class="control-label" style="width:200px;margin-right:20px"><strong>First name</strong></label>
<div class="controls">
<%= f.text_field :first_name, :placeholder => 'First name', :class => '', :style => '' %>
</div>
</div>
<div class="control-group">
<label class="control-label" style="width:200px;margin-right:20px"><strong>Last name</strong></label>
<div class="controls">
<%= f.text_field :last_name, :placeholder => 'Last name', :class => '', :style => '' %>
</div>
</div>
<div class="control-group">
<label class="control-label" style="width:200px;margin-right:20px"><strong>Email</strong></label>
<div class="controls">
<%= f.text_field :email, :placeholder => 'Your email', :class => '', :style => '' %>
</div>
</div>
<div class="control-group">
<label class="control-label" style="width:200px;margin-right:20px"><strong>Phone</strong></label>
<div class="controls">
<%= f.text_field :phone, :placeholder => 'Your phone number', :class => '', :style => '' %>
</div>
</div>
<div class="form-actions">
<%= f.submit "Save Changes", :class => 'btn btn-success' %>
<%= link_to 'Cancel', leads_path, :class => 'btn' %>
</div>
<% end %>

You shouldn't need to supply a method nor an action for a simple form like this. A simple
<% form_for #agent do |f| %>
should do you. Have you tried that? Are there any other forms on the page that could be conflicting? If so, try removing those other forms first, then see how that goes.

Fixed it. This post covered the exact same issue: HTML <form> tag causing Rails form to submit a GET instead of POST request
The GET request is being caused by a form tag around the rails form which was there to add the twitter bootstrap styling class "form-horizontal". Removed the extra form tag and it works fine.

Related

search function not working - Ruby on rails

I'm new to Ruby on Rails and trying to implement a search function with simple form to filter out availabilities results. After I press search button, it still stays on the same page and not running the search function in the controller. The permitted is false. I'm wondering why this might occur. Is there anything wrong with the search_params I wrote?
Rails version is 6.0.2.1.
views/availabilities/_searchform.html.erb
<form>
<div id="aDiv">
<%= simple_form_for :search, :url => search_rides_result_path, :method => :get do |f| %>
<div class="form-row">
<div class="form-group col-md-2">
<%= f.input :start_city, label: 'Start City', class: "form-control", error: 'Start address is mandatory, please specify one' %>
</div>
<div class="form-group col-md-4">
<%= f.input :start_street_address, label: 'Start Street Address', class: "form-control" %>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-2">
<%= f.input :end_city, label: 'Destination City', class: "form-control" %>
</div>
<div class="form-group col-md-4">
<%= f.input :end_street_address, label: 'Destionation Street Address', class: "form-control" %>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<%= f.input :trip_time, as: :datetime, inline_label: 'Yes, remember me', class: "form-control" %>
</div>
<div class="form-group col-md-2">
<%= f.input :lowest_acceptable_price, label: 'Expected Price', class: "form-control" %>
</div>
</div>
<%= f.submit "Search", class: "btn btn-primary" %>
<% end %>
</div>
</form>
routes.rb file.
get 'search_rides', to: "availabilities#index"
get 'search_rides_result', to: "availabilities#search"
availabilities_controller.rb
def index
#availabilities = Availability.unmatched
end
def search
#availabilities = Availability.unmatched.search(search_params[:start_city])
end
def search_params
params.require(:search).permit(:start_city, :start_street_address, :end_city, :end_street_address, :trip_time, :lowest_acceptable_price)
end
models/availability.rb
class Availability < ApplicationRecord
has_many :users, :through => :posts
has_one :request
scope :unmatched, ->{ where(matched_request_id: -1) }
def self.search (params)
puts "start searching"
results = city_matches(start_city, end_city, params[:start_city], params[:end_city])
return nil unless results
results
end
Instead of using 2 different methods for search, try combining both in index method. Your index method will now look as follows:
def index
if params[:search]
#availabilities = Availability.unmatched.search(search_params[:start_city])
else
#availabilities = Availability.unmatched
end
end
Change the form url to search_rides_path. This way search results will be rendered in same view upon form submission.

Rails Devise Login 401 Unauthorized

What I am trying to do
I am trying to set up the Authentication with Devise in the Session Controller, methods new and create.
I am using Rails 5 and I customized the View new.html.erb.
What is the problem
I am not able to authenticate successfully after signing out from the Account. The problem is connected with the sign_in_params hash, which is passed blank to the new method of the session_controller
Testing of the functionality
I conducted a test of the Login, by including a breakpoint in my Account::SessionsController, I noticed that the sign_in_params hash was blank, then the program exits with 401 Unauthorized.
8: def new
9: self.resource = resource_class.new(sign_in_params)
=> 10: clean_up_passwords(resource)
11: yield resource if block_given?
12: respond_with(resource, serialize_options(resource))
13: end
sign_in_params => {}
My Code
I was able by resetting my code to identify the cause of my problem. It is connected to the custom Devise View that I modified in app/views/devise/sessions/new.html.erb
This is the code:
<form class="login-form" action="index.html">
<div class="login-wrap">
<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
<p class="login-img"><i class="icon_lock_alt"></i></p>
<div class="field">
</div>
<div class="input-group">
<span class="input-group-addon"><i class="icon_profile"></i></span>
<%= f.email_field :email, autofocus: true, :class => "form-control", :placeholder => "Username" %>
<!--<input type="text" class="form-control" placeholder="Username" autofocus>-->
</div>
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<%= f.password_field :password, autocomplete: "off", :class => "form-control", :placeholder => "Password" %>
</div>
<% if devise_mapping.rememberable? -%>
<label class="checkbox">
<%= f.check_box :remember_me %>
<%= f.label :remember_me, :class => "remember_me_Label" %>
<span class="pull-right"> <%= link_to "Forgot Password?", {}, :id => "lostPw" %></span>
</label>
<% end -%>
<%= f.submit "Login", :class => "btn btn-primary btn-lg btn-block" %>
<%= link_to "Signup", new_account_registration_path, :method => :get, class: "btn btn-info btn-lg btn-block signuptext" %>
<% end %>
</div>
</form>
In the log, I have the following important informations, but no errors:
Started GET "/account/index.html?utf8=%E2%9C%93&authenticity_token=s1aA%2FNcZo1HIkF1qJOlrIAlM9rJM3y1ced8tQLiWnGsSugBVs0AYKVJR8QLa1I%2BT500sYu7H1%2BPQ2UwH3JG2ew%3D%3D&account%5Bemail%5D=test%40email.com&account%5Bpassword%5D=[FILTERED]&account%5Bremember_me%5D=0&commit=Login" for 127.0.0.1 at 2017-02-06 19:16:04 +0100 (pid:8311)
2017-02-06 19:16:04.557 [fyi] Processing by AccountController#index as HTML (pid:8311)
2017-02-06 19:16:04.557 [fyi] Parameters: {"utf8"=>"✓", "authenticity_token"=>"s1aA/NcZo1HIkF1qJOlrIAlM9rJM3y1ced8tQLiWnGsSugBVs0AYKVJR8QLa1I+T500sYu7H1+PQ2UwH3JG2ew==", "account"=>{"email"=>"test#email.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Login"} (pid:8311)
2017-02-06 19:16:04.558 [fyi] Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms) (pid:8311)
Following is the solution of the problem
Thanks
Fabrizio Bertoglio
Solution
The problem is in the html code of new.html.erb, as I did not remove the html <form> tags from the html and this would cause problems with my <%= form_for > <% end %> rails tag. This is the reason why strong_params is empty.
The form was not submitting any value to the controller, the problem could have been easily discovered by debugging directly the new.html.erb view instead of the controller.
Was helpful having the input from Max, that suggested me to restart all over with Devise, so that I could understand that the problem was connected with the form and not with rails strong parameters.
This is the correct new.html.erb.
<%= form_for(resource, as: resource_name, url: session_path(resource_name), html: { class: "login-form"}) do |f| %>
<div class="login-wrap">
<p class="login-img"><i class="icon_lock_alt"></i></p>
<div class="input-group">
<span class="input-group-addon"><i class="icon_profile"></i></span>
<%#= f.label :email %>
<%= f.email_field :email, autofocus: true, :class => "form-control", :placeholder => "Username" %>
<!--<input type="text" class="form-control" placeholder="Username" autofocus>-->
</div>
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<%#= f.label :password %>
<%= f.password_field :password, autocomplete: "off", :class => "form-control", :placeholder => "Password" %>
</div>
<% if devise_mapping.rememberable? -%>
<label class="checkbox">
<%= f.check_box :remember_me %>
<%= f.label :remember_me, :class => "remember_me_Label" %>
<span class="pull-right"> <%= link_to "Forgot Password?", {}, :id => "lostPw" %></span>
</label>
<% end -%>
<%= f.submit "Login", :class => "btn btn-primary btn-lg btn-block" %>
<%= link_to "Signup", new_registration_path(resource_name), :method => :get, class: "btn btn-info btn-lg btn-block signuptext" %>
<div class="links ">
<%= render "devise/shared/links2" %>
</div>
</div>
<% end %>
<div class="text-right">
<div class="credits">
<!--
All the links in the footer should remain intact.
You can delete the links only if you purchased the pro version.
Licensing information: https://bootstrapmade.com/license/
Purchase the pro version form: https://bootstrapmade.com/buy/?theme=NiceAdmin
-->
Business Bootstrap Themes by BootstrapMade
</div>
</div>
</div>

Customize the devise edit method - Rails 4

I have a problem with customising Devise method. I want to edit an existing profile. But it doesn't change.
Here's my code
My controller:
class DashboardController < Users::RegistrationsController::ApplicationController
def index
end
def update
#user = current_user
if #user.update_attributes(user_params)
redirect_to 'index', :notice => "Successfully updated profile."
else
Rails.logger.info(#user.errors.messages.inspect)
render :action => 'edit'
end
end
def edit
end
private
def user_params
params.require(:user).permit(:avatar, :username, :email, :password, :password_confirmation)
end
end
My edit view
<div class="container sign-in-up">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<br>
<div class="text-center">
<h1><b>Edit the profile</b> </h2>
<div class="tab-content">
<div class="tab-pane fade in active" id="new">
<fieldset>
<div class="form-group">
<div class="right-inner-addon">
<i class="fa fa-envelope"></i>
<%= form_for current_user, url: edit_dashboard_path(current_user), html: { method: :get, multipart: true } do |f|%>
<div class="home_field " >
<%= f.label :username%>
<br/>
<%= f.text_field :username, autofocus: true, :placeholder => 'Username', class:"form-control input-lg " %>
</div>
<div class="home_field ">
<%= f.label :email %>
<br/>
<%= f.email_field :email, autofocus: true, :placeholder => 'Email' , class:"form-control input-lg" %>
</div>
<div class="home_field ">
<%= f.label :password%>
<br/>
<%= f.password_field :password, :placeholder => 'Password', class:"form-control input-lg"%>
</div>
<div class="home_field ">
<%= f.label :password_confirmation%>
<br/>
<%= f.password_field :password_confirmation,:placeholder => 'Confirm your password' , class:"form-control input-lg"%>
</div>
<div class ="home_field">
<%= f.file_field :avatar %>
<br>
</div>
<div>
</div>
<div class="home_field">
<%= f.submit 'Edit the profile', class: "btn btn-primary btn-lg btn-block btn-group" %>
<br/>
</div>
<% end %>
</fieldset>
It can be a problem in my layout code, where i make the link to the edit page
<%= link_to "Edit the Profile", edit_dashboard_path %>
Your form is submitting to the edit dashboard using a get, which is the same page you are on. Instead you want to update the current user something like this:
<%= form_for current_user, html: { multipart: true } do |f|%>
This will default to the update attribute and CRUD action defined in your routes file for a user
I would suggest changing this line:
<%= form_for current_user, url: edit_dashboard_path(current_user), html: { method: :get, multipart: true } do |f|%>
In the url use your path to the 'update' method, not the edit (use rake routes on your command line)
In the method use :put instead of :get

Rails : I made form_for to post data to certain action but it doen't work

Now I'm trying to use mailgun gem to send e-mail. So I made a form_for help like this.
Here is my index.html.erb file.
<form class="form-horizontal">
<fieldset>
<legend>FEEDBACK</legend>
<div class="form-group col-md-12" align="center">
<%= form_for :feedback, url: feedback_path do |f| %>
<%= f.text_area :contents, class: "form-control", style: "width:112%", :rows => 5 , :autocomplete => :off %>
<% unless user_signed_in? %>
<div class="col-md-12" style="height: 10px"></div>
<%= f.text_field :from, class: "form-control", style: "width:112%", :autocomplete => :off, :placeholder => "Leave your email" %>
<% end %>
<div class="col-md-12" style="height: 10px"></div>
<%= f.submit "Send", class: "btn btn-default" %>
<% end %>
</div>
</fieldset>
</form>
And this is my home_controller.rb file.
class HomeController < ApplicationController
def feedback_send
from = params[:feedback][:from]
contents = params[:feedback][:contents]
FeedbackMailer.feedback_email(from, contents).deliver_now
redirect_to :back
end
This is routes.rb file
post '/feedback_send', to: 'home#feedback_send', as: 'feedback'
But It doesn't work. It redirected to "http://localhost:3000/?utf8=%E2%9C%93&authenticity_token=Whcu6QAF5XGBwYIv8A%2B2r6KvOyXIqc9jC%2BB1y%2Fp4zXQ%3D&feedback%5Bcontents%5D=12312321312&feedback%5Bfrom%5D=&commit=Send".
When I look at log of server, it shows like this.
Started GET "/?utf8=%E2%9C%93&authenticity_token=Whcu6QAF5XGBwYIv8A%2B2r6KvOyXIqc9jC%2BB1y%2Fp4zXQ%3D&feedback%5Bcontents%5D=12312321312&feedback%5Bfrom%5D=&commit=Send" for 127.0.0.1 at 2015-09-06 22:08:00 +0900
I can't catch what is wrong here.

Rails 4 - How to populate remote content in a form?

Here is what I have
I have a method like this in my bookmarks_controller.rb
def fetch
#result = LinkThumbnailer.generate(params[:url])
end
I have the following form fields to create new bookmarks
url
title
description
thumbnail
tags
So my new.html.erb looks like this
<%= form_for(#bookmark, :html => {class: "panel-body"}) do |f| %>
<% if #bookmark.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#bookmark.errors.count, "error") %> prohibited this bookmark from being saved:</h2>
<ul>
<% #bookmark.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="block">
<%= f.label :url, :class => 'control-label' %>
<%= f.text_field :url, :class => 'form-control', :placeholder => 'URL' %>
</div>
<div class="block">
<%= f.label :title, :class => 'control-label' %>
<%= f.text_field :title, :class => 'form-control', :placeholder => 'Title' %>
</div>
<div class="block">
<%= f.label :description, :class => 'control-label' %>
<%= f.text_area :description, rows: 6, :class => 'form-control', :placeholder => 'Description' %>
</div>
<div class="block">
<%= f.label :thumbnail, :class => 'control-label' %>
<%= f.text_field :thumbnail, :class => 'form-control', :placeholder => 'Thumbnail url' %>
</div>
<div class="block">
<%= f.label :tag_list, :class => 'control-label' %>
<%= f.text_field :tag_list, :class => 'form-control', :placeholder => 'Tags (separated by commas)' %>
</div>
<div class="actions">
<%= f.submit :class => "btn btn-info" %>
</div>
<% end %>
I would like to have a button called Fetch right next to url field.
When user click Fetch button, I would like to populate the form fields using ajax.
I viewed rails documentation. It says to add remote: true attribute to the form.
But I wanna use ajax function only when the user click fetch button.
Can someone help me with this?
Thankyou
You can generate an object using the LinkThumbnailer gem and than convert it to json
with this action:
def fetch
#result = LinkThumbnailer.generate(params['given_url'])
respond_to do |format|
format.json do
result.to_json
end
end
end
And in your view you could use the Jquery getJSON method to access the #fetch action and pass the given url as a parameter:
<script type="text/javascript">
require(['jquery'], function($) {
$('.fetch-button-class').change(function() {
var given_url = $('.url-class').val();
$.getJSON('<%= fetch_action_url %>', {'given_url': given_url }, function(obj) {
$('.title-class').val(object.title);
$('.description-class').val(object.description);
});
});
});
</script>

Resources