I am using simple_form in rails, and I have this as checkbox:
<%= f.input :delivery_days, as: :check_boxes,
collection: [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Satusday',
'All'],
wrapper: :vertical_radio_and_checkboxes
%>
I am not able to get the values of selected checkboxes in my controller.
I am using the following code to get it:
def user_basic_params
logger.info "from user_basic_params"
params.require(:profile).permit(:delivery_days[])
end
I have other form fields but they are getting handled correctly and I am able to get their values.
Console output is :
Started POST "/profiles" for 127.0.0.1 at 2015-06-02 02:07:56 +0530
Processing by ProfilesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"w3RvztJtKq56qimpZPj3KD9S5pr1vbw2K6b7eToaEV5rEuBsx1jqJ8gITg+uHq8TgBoeYZPsczQLghWg2fhpCg==", "profile"=>{"milk_animal"=>"Any", "milk_type"=>"Any", "brand"=>"Amul", "time_of_delivery(1i)"=>"2015", "time_of_delivery(2i)"=>"6", "time_of_delivery(3i)"=>"1", "time_of_delivery(4i)"=>"20", "time_of_delivery(5i)"=>"37", "start_date(1i)"=>"2015", "start_date(2i)"=>"6", "start_date(3i)"=>"1", "delivery_days"=>["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Satusday", "All", ""], "name"=>"Sony", "address"=>"asdfghjk", "pincode"=>"zxcvbnm,", "contact_no"=>"2345678"}, "commit"=>"Create Profile"}
from create
from user_basic_params
Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)
ArgumentError (wrong number of arguments (0 for 1..2)):
app/controllers/profiles_controller.rb:53:in `[]'
app/controllers/profiles_controller.rb:53:in `user_basic_params'
app/controllers/profiles_controller.rb:18:in `create'
The problem is in the permit(:delivery_days[]) part of your code. Rails expects the brackets to contain 1 or 2 parameters, but you are passing none, thus raising an error.
I am not sure why the brackets are there, try removing them and I believe your code should work.
Replace this
params.require(:profile).permit(:delivery_days[])
with
params.require(:profile).permit(:delivery_days)
Related
A rails form that posts
<%= form_with url: search_results_labours_path do |f| %>
gets processed by the controller, but fails to return the expected XHR response with
Started POST "/labours/search_results" for ::1 at 2021-02-12 10:12:46 +0100
Processing by LaboursController#search_results as JS
[...]
ActionController::UnknownFormat (LaboursController#search_results is missing a template for
this request format and variant.
request.formats: ["text/javascript", "*/*"]
request.variant: []):
Yet, the template does exist
and it calls a partial _search_results.html.erb
$("div#search_results").html("<%= j render ('labours/results') %>").css({ opacity: 0 }).fadeTo('slow',1);
def search_results
#labours = Labour.order(usercontract_id: :asc).where('time_start >= ?', params[:labour][:date_start].to_date.at_beginning_of_day ).all
index_personnel
end
Why does rails not see the template for that action?
Update
changing the form to a remote
<%= form_with(url: search_results_labours_path, local: true) do |f| %>
and processing the partial as a non partial search_results.html.erb processes entirely as expected, confirming the problem is in perceiving the existence of search_results.js.erb The file also appears, with this spelling via the console to list all files.
-rw-r--r--# 1 deploy staff 105 12 Feb 10:10 search_results.js.erb
So this is a pretty basic Rails 5 application using Docker, which includes some user authentication that I built from scratch (not using Devise etc). Now, I want to start learning about request specs with Capybara, but I'm hitting what seems like a pretty strange issue with it.
Here's my login form (sessions.new.erb):
<%= form_tag sessions_path do %>
<form class="m-t" role="form" action="/">
<div class="form-group">
<%= text_field_tag :email, params[:email], class: 'form-control', placeholder: "Email Address", required: "" %>
</div>
<div class="form-group">
<%= password_field_tag(:password, nil, class: 'form-control', placeholder: "Password", required: "") %>
</div>
<div class="form-group">
<%= check_box_tag :remember_me, 1, params[:remember_me] %>
<%= label_tag :remember_me %>
</div>
<div class="actions"><%= submit_tag "Log In", class: "btn btn-primary block full-width m-b" %></div>
</form>
<% end %>
And my requests/sessions_spec.rb:
require "rails_helper"
RSpec.feature "Login", :type => :feature do
scenario "handles wrong email and password gracefully" do
visit login_path
fill_in "Email Address", :with => "something"
fill_in "Password", :with => "something"
click_button "Log In"
expect(page).to have_text("Email or password incorrect")
end
end
Now, this works if you test it manually so I would presume Capybara would see the same thing. But it kept failing. I've got the application configured so that if you try and access a protected controller and you're not logged in, it redirects you to /login and flashes a message to say Please log in to see this page. The Rspec test was returning that, which was weird - that suggested that Capybara was trying to visit another page.
So I tailed the test logs (docker-compose run web tail -f log/test.log)
And what I found is puzzling me:
Started GET "/login" for 127.0.0.1 at 2017-10-17 06:59:26 +0000
Processing by SessionsController#new as HTML
Rendering sessions/new.html.erb within layouts/empty
Rendered sessions/new.html.erb within layouts/empty (1.1ms)
Completed 200 OK in 6ms (Views: 6.1ms | ActiveRecord: 0.0ms)
Started GET "/?email=something&password=[FILTERED]&commit=Log+In" for 127.0.0.1 at 2017-10-17 06:59:26 +0000
Started GET "/locations" for 127.0.0.1 at 2017-10-17 06:59:26 +0000
Processing by LocationsController#index as HTML
Redirected to http://www.example.com/login
Filter chain halted as :authenticate rendered or redirected
Completed 302 Found in 2ms (ActiveRecord: 0.0ms)
Started GET "/login" for 127.0.0.1 at 2017-10-17 06:59:26 +0000
Processing by SessionsController#new as HTML
Rendering sessions/new.html.erb within layouts/empty
Rendered sessions/new.html.erb within layouts/empty (1.1ms)
Completed 200 OK in 6ms (Views: 4.9ms | ActiveRecord: 0.0ms)
(0.4ms) ROLLBACK
The first bit is okay, GET Login is processed by the SessionsController#new. But then, (see line 6) for some reason Capybara tried to GET the root URL, passing the email/password params in. My root URL is mapped to the LocationsController#index, which the user isn't allowed to access, so gets redirected back to /login with the message Please log in to see this page. What that button actually does is send a POST to SessionsController#create. And if you watch the logs when you do it manually, that's exactly what happens:
web_1 | Started POST "/sessions" for 172.18.0.1 at 2017-10-17 07:02:19+0000
web_1 | Processing by SessionsController#create as HTML
I can't work out why in Capybara when you press the button it performs a completely different request to when you click the button manually.
Help greatly appreciated!
A couple of clarifications first.
You're not writing request specs, you're writing feature specs (as evidenced by the use of RSpec.feature and :type => :feature
You don't need to specify :type => :feature when using RSpec.feature since that's already set.
Now on to your issue. You have nested forms in your view code since form_tag creates a <form>element and then you have another <form> element directly inside that (Note: it's always better to post the actual HTML rather than the erb so people can see what the actual HTML is). Combine that with the fact you appear to be using the rack-test driver (no js: true metadata) which won't behave the same way as a real browser when the HTML is invalid (which nested forms are), and you end up with your current behavior. I would guess when you use it with a real browser the inside form element is ignored and the outer form element has a method attribute equal to "post" so it gets posted. When using rack-test it's probably submitting the inner form element which has no method attribute and therefore defaults to "get". Remove the extraneous <form class="m-t" role="form" action="/"> form element from your view and things should work.
Rails 4.1 is adding a strange object to my POST parameters, which is a duplicate of the data I post.
As a very basic test, I post a simple {"msg"=>"hello word!"} from Angular:
$http.post('/commands/save.json', {msg:'hello word!'}).
Rails gets:
Started POST "/commands/save.json" for ::1 at 2015-01-08 10:15:55 -0800
ActiveRecord::SchemaMigration Load (0.3ms) SELECT `ngconf_schema_migrations`.* FROM `ngconf_schema_migrations`
Processing by CommandsController#save as JSON
Parameters: {"msg"=>"hello word!", "command"=>{"msg"=>"hello word!"}}
{
"msg" => "hello word!",
"controller" => "commands",
"action" => "save",
"format" => "json",
"command" => {
"msg" => "hello word!"
}
}
Commands Load (0.3ms) SELECT `ngconf_commands`.* FROM `ngconf_commands`
Completed 200 OK in 16ms (Views: 1.5ms | ActiveRecord: 12.8ms)
Basically I am trying to understand where does this come from and how to stop it. I do not remember Rails 4.0 doing this.
"command" => {
"msg" => "hello word!"
}
This is coming from ParamsWrapper. You can disable this by specifying wrap_parameters false in the controller. If you would like to disable it application wide, edit your config/initializers/wrap_parameters.rb and set the :format option to an empty array as per the comments. As an example
# Be sure to restart your server when you modify this file.
#
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: []
end
Afternoon All,
Been trying to figure out where this is coming from but cannot understand why I get the following, here is my select_tag.
<%= select_tag :area_of_focus, options_for_select(User::LANGUAGES), {multiple: true, include_blank: false} %>
Here is the constant:
LANGUAGES = ["Rails", "Ruby", "Javascript", "C#", "HTML", "CSS", "SQL" ]
When I run the submit on update I get the following validation error on area_of_focus. First this is from the rails console log,
"area_of_focus"=>["Javascript"]
and this is from the debug on my page:
area_of_focus: ! '["Javascript"]'
UPDATE: Just noticed that my params listed below, :area_of_focus is sitting outside the user hash:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ZAAObfDDIUumIJV2cQjkZSkaUY6RsHbdFY1MEd28hvI=", "user"=>{"company_name"=>"kdkdsh", "street"=>"ksakjakjs", "city"=>"kjsdkjskds", "state"=>"kdjsksksj", "postcode"=>"ksdjkssk", "employer_desc"=>"kdjskksdhdsjs", "number_of_employees"=>"100", "email"=>"shaun#shaun1.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "current_password"=>"[FILTERED]"}, "area_of_focus"=>["Ruby", "Javascript"], "commit"=>"Update"}
What have I done incorrectly here?
try: <%= form.select :area__of_focus, ....
I have a quite standard Devise login procedure with:
View:
resource_name, :url => session_path(resource_name)) do |f| %>
<%= f.input :password, input_html: {class: "span6"} %>
<% if devise_mapping.rememberable? -%>
<p><%= f.check_box :remember_me %> Remember me</p>
<% end -%>
<input type="hidden" name="after_sign_in_page" value="<%=#after_sign_in_page%>">
<p><%= f.submit "Sign in", class: "btn btn-success" %></p>
And I just created a sessioncontroller to downcase the email:
class SessionsController < Devise::SessionsController
def create
params[:user][:email].downcase!
super
logger.debug "Errors: #{resource.errors}"
end
A login with good credentials happens fine.
With wrong credentials, It redirects to the sign-in page with this log:
Started POST "/users/sign_in" for 127.0.0.1 at 2013-01-10 09:59:44 +0100
Processing by SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8eytQkr20JOOOdDvpCWakbmUzNoaHMxK9/BSEVxETik=", "user"=>{"email"=>"nicolas#demoreau.be", "password"=>"[FILTERED]", "remember_me"=>"0"}, "after_sign_in_page"=>"", "commit"=>"Sign in"}
Time zone: (GMT+00:00) UTC, current area: , user to register: , current controller: sessions
Completed 401 Unauthorized in 69ms
Processing by SessionsController#new as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8eytQkr20JOOOdDvpCWakbmUzNoaHMxK9/BSEVxETik=", "user"=>{"email"=>"nicolas#demoreau.be", "password"=>"[FILTERED]", "remember_me"=>"0"}, "after_sign_in_page"=>"", "commit"=>"Sign in"}
Rendered devise/sessions/_new.html.erb (17.8ms)
Rendered devise/sessions/new.html.erb within layouts/application (19.7ms)
Rendered layouts/_header.html.erb (66.1ms)
Completed 200 OK in 173ms (Views: 98.3ms | ActiveRecord: 0.9ms)
Apparently the 401 is dropped by Warden but I couldn't figure out why.
The user is correctly redirected back to the login page but there is no error message displayed (which is normal as they are wiped out by the redirect)
What am I doing wrong?
thanks!
EDIT 1:
For now, I found a quick hack. I added this in SessionsController#new
if params[:user]
flash[:alert] = "Incorrect login or password"
end
Not very elegant but at least, I have something.
First of all, let me advice you against overriding Devise controllers:
In this case, Devise takes care of transforming the email to lower
case for you, so there's really no need to overwrite the create method.
Your app will support Devise updates seamlessly if you stick to the
standard.
Also, Devise should set a flash error automatically, make sure you're displaying it in your view.
The status code 401 is just a standard response for unauthorized requests.
401 Unauthorized is similar to 403 Forbidden, but specifically for use
when authentication is required and has failed or has not yet been
provided
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
You should definitely consider dropping your custom controller,
Cheers
Your flash message is not going to be set because Devise::SessionsController#create calls warden for the authentication which, in case of failures, will call Devise::FailureApp. Your controller never handles the failure scenarios.
If you want a custom message, you can customize the failure app for that, there are some articles in the Devise wiki explaining how to do so.
But in general, you can customize your failure messages via I18n and there is probably a better way to achieve what you want without a need to override Devise controllers.
I agree with jassa, just update your Devise version (with bundle update devise).
Case insensitive emails are already present in Devise, just make sure you have this config:
# devise.rb
Devise.setup do |config|
config.case_insensitive_keys = [:email ]
end
In any case, since you seem to be missing some flash messages and this config, perhaps it would better if you just re-ran the generator:
rails generate devise:install
You should then let Devise overwrite some files, just make sure you backup yours first.