I'm allowing a user to enter IP addresses in an input field which may be of different types delimited by a comma, such as (in no particular order):
192.168.1.1,192.168.2.1-25,10.10.10.0/24,192.168.1.2
This 'string' would get saved in my DB under device.ips_to_scan.
I want to validates_format_of on these, but am finding it a little difficult to write a regex that seems to work in rails, while it does work on regex101 (https://regex101.com/r/nf2bnM/1):
validates_format_of :ips_scan, with: /\A([0-9]{1,3}\.){3}[0-9]{1,3}(\/([1-2][0-9]|[0-9]|3[0-2]))?(-([0-9]{1,3}))?,?\Z/i, on: :update
This one is expected to fail:
Started PUT "/devices/2" for 127.0.0.1 at 2018-02-19 22:03:15 -0500
Processing by DevicesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"EQCFG6/xoJHtP6Nd3oqaYRW6mypfEoCMrnio1yj6loP+KtvjgLZ9Gmhb0oTwCjD0RGH+qQuctZFVIvF5HBJcGw==", "device"=>{"ips_scan"=>"192.168.1.1,192.168.2.1-25,a.b.c.d", "ips_exclude"=>"10.10.10.1"}, "commit"=>"Save", "id"=>"2"}
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 2], ["LIMIT", 1]]
Device Load (1.6ms) SELECT "devices".* FROM "devices" WHERE "devices"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
(0.5ms) BEGIN
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
(0.5ms) ROLLBACK
Redirected to http://localhost:3000/devices/2/edit
Completed 302 Found in 47ms (ActiveRecord: 12.1ms)
...But this one should have worked:
Processing by DevicesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"JJfmT/0l5MEDc+gUH/WHHp3bbgyzjGa0xTzaXM3E/WHLvbi30mI5SoYXmc0xdS2LzAALj+cCU6k+ZoPy+Sw3+Q==", "device"=>{"ips_scan"=>"192.168.1.1,192.168.2.1-25,192.168.1.2", "ips_exclude"=>"10.10.10.1"}, "commit"=>"Save", "id"=>"2"}
User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 2], ["LIMIT", 1]]
Device Load (0.7ms) SELECT "devices".* FROM "devices" WHERE "devices"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
(0.6ms) BEGIN
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
(0.6ms) ROLLBACK
Redirected to http://localhost:3000/devices/2/edit
Completed 302 Found in 17ms (ActiveRecord: 3.5ms)
Last thing I can think of, is that I do have strong parameters, but I'm permitting ips_scan, so that this shouldn't be an issue:
def update
if #device.update(device_params)
flash[:notice] = 'Successful update'
respond_with :edit, :device
else
flash[:warning] = 'Unable to update'
respond_with :edit, :device
end
end
private def device_params
params.require(:device).permit(:token, :ips_scan, :ips_exclude)
end
I'm hoping you rubyist's out there have a eloquent solution. The first thought that comes to mind is that I have to split the string, and check each element sequentially to ensure it matches instead.
While I'm still open to a nice eloquent one-liner within the Model itself, I was able to get this working through creating a concern:
models/concerns/ip_validator.rb
class IpValidator < ActiveModel::Validator
def validate(record)
ips = record.ips_scan.split(',')
ips.each do |ip|
/([0-9]{1,3}\.){3}[0-9]{1,3}(\/([1-2][0-9]|[0-9]|3[0-2]))?(-([0-9]{1,3}))?/ =~ ip
record.errors.add(:ips_scan, ' is not valid') unless $LAST_MATCH_INFO
end
end
end
The call in my model now looks like:
validates :ips_scan, :ips_exclude, ip: true, on: :update
You can use this method in your custom validator to check an IP address
require 'ipaddr'
def valid_ip_addr?(ip_addr)
IPAddr.new(ip_addr)
true
rescue IPAddr::InvalidAddressError => _error
false
end
Related
Whenever I try to update the user, I get redirected to /users with the edit form filled in but no errors.
Users::RegistrationsController
class Users::RegistrationsController < Devise::RegistrationsController
before_action :configure_account_update_params, only: [:update]
def update
super
end
def configure_account_update_params
devise_parameter_sanitizer.permit(:account_update, keys: [:name,:property,:admin,:phone_number,:organization,:gender,:profile_pic,:birthday])
end
...
end
Rails Server Logs
Started PUT "/users" for ::1 at 2020-07-22 17:55:57 +0500
Processing by Users::RegistrationsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"iqpDtwA8U1jJ10dtaCV/eE0m96KHUa8G7tWrpOLA48AXYnUjT+6M2qwrwncjThvwQnQQycn/dNCWsbnsteJmhA==", "user"=>{"name"=>"Sohail ", "phone_number"=>"(11", "organization"=>"11", "email"=>"user#test.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "current_password"=>"[FILTERED]"}, "commit"=>"Update"}
User Load (1.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 8], ["LIMIT", 1]]
User Load (1.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 8], ["LIMIT", 1]]
User Exists (1.1ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 AND "users"."id" != $2 LIMIT $3 [["email", "user#test.com"], ["id", 8], ["LIMIT", 1]]
Rendering users/registrations/edit.html.erb within layouts/application
Rendered users/registrations/edit.html.erb within layouts/application (3.9ms)
StripeCustomer Load (4.6ms) SELECT "stripe_customers".* FROM "stripe_customers" WHERE "stripe_customers"."user_id" = $1 LIMIT $2 [["user_id", 8], ["LIMIT", 1]]
Rendered layouts/_header.html.erb (97.4ms)
Rendered layouts/_footer.html.erb (15.5ms)
Completed 200 OK in 681ms (Views: 310.2ms | ActiveRecord: 9.0ms)
It seems you have messed a little with your parameters. You sent nested parameters on your form like this:
"user"=>{"name"=>"Sohail ", "phone_number"=>"(11", "organization"=>"11", "email"=>"user#test.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "current_password"=>"[FILTERED]"}, "commit"=>"Update"}
However your permited parameters assume you are nesting everything on a :account_update key.
So you could either change the key sent on your form, or use this sanitizer:
def configure_account_update_params
devise_parameter_sanitizer.permit(:account_update, keys: [:name,:property,:admin,:phone_number,:organization,:gender,:profile_pic,:birthday])
end
Does Rails actually cache the query result? The documentation says that same query will be never executed twice on the same request:
1.7 SQL Caching
The second time the same query is run against the database, it's not actually going to hit the database. The first time the result is returned from the query it is stored in the query cache (in memory) and the second time it's pulled from memory.
I did an experiment to proof that Rails actually cache the query:
def test
data = ""
User.find(1).update(first_name: 'Suwir Suwirr')
data << User.find(1).first_name
data << "\n"
User.find(1).update(first_name: 'Pengguna')
data << User.find(1).first_name
data << "\n"
render plain: data
end
If the result is cached, i would get the same result for each User.find(1). However, the result was Rails does not actually cache the query; i was expecting the update does not reflected on the result since it was "cached":
Suwir Suwirr
Pengguna
But the console says that it was cached: (Please highlight the CACHE word)
Started GET "/diag/test" for 10.0.2.2 at 2017-02-21 10:30:16 +0700
Processing by DiagController#test as HTML
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 4], ["LIMIT", 1]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
(0.1ms) BEGIN
SQL (0.4ms) UPDATE "users" SET "first_name" = $1, "updated_at" = $2 WHERE "users"."id" = $3 [["first_name", "Suwir Suwirr"], ["updated_at", 2017-02-21 03:30:16 UTC], ["id", 1]]
(16.5ms) COMMIT
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
(0.1ms) BEGIN
SQL (0.3ms) UPDATE "users" SET "first_name" = $1, "updated_at" = $2 WHERE "users"."id" = $3 [["first_name", "Pengguna"], ["updated_at", 2017-02-21 03:30:16 UTC], ["id", 1]]
(0.9ms) COMMIT
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
Rendering text template
Rendered text template (0.0ms)
Completed 200 OK in 380ms (Views: 3.5ms | ActiveRecord: 21.9ms)
So my question, does Rails actually cache the query result? Or, only several query result on some request?
Update: Using Batch #update_all
I made another experiment to "fool" the query logic. Now Rails does not "cache" the query. Why this behaviour can happen?
# Controller
def test
data = ""
User.where(id: 1).update_all(first_name: 'Suwir Suwirr')
data << User.find(1).first_name
data << "\n"
User.where(id: 1).update_all(first_name: 'Pengguna')
data << User.find(1).first_name
data << "\n"
logger.info 'hi'
render plain: data
end
# Console
Started GET "/diag/test" for 10.0.2.2 at 2017-02-21 10:45:43 +0700
Processing by DiagController#test as HTML
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 4], ["LIMIT", 1]]
SQL (13.8ms) UPDATE "users" SET "first_name" = 'Suwir Suwirr' WHERE "users"."id" = $1 [["id", 1]]
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
SQL (2.9ms) UPDATE "users" SET "first_name" = 'Pengguna' WHERE "users"."id" = $1 [["id", 1]]
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
hi
Rendering text template
Rendered text template (0.0ms)
Completed 200 OK in 28ms (Views: 0.8ms | ActiveRecord: 17.8ms)
# Browser result
Suwir Suwirr
Pengguna
I was stupid.
Yes, Rails does actually cache the query, but update and destroy will invalidate its query cache. update_all is basically iterating each record with update.
I tried the experiment by really "fooling" the ActiveRecord query mechanism. And yes, it works.
# Controller
def test
data = ""
ActiveRecord::Base.connection.execute('UPDATE "users" SET "first_name" = \'Suwir Suwirr\' WHERE "users"."id" = 1')
data << User.find(1).first_name
data << "\n"
ActiveRecord::Base.connection.execute('UPDATE "users" SET "first_name" = \'Pengguna\' WHERE "users"."id" = 1')
data << User.find(1).first_name
data << "\n"
render plain: data
end
# Browser
Suwir Suwirr
Suwir Suwirr
I want to approve the user to be vip,but when I press the button.The page refreshed but nothing changed.The log in terminal is
Started POST "/admin/users/26/approve_vip" for ::1 at 2016-12-12 16:33:22 +0800
Processing by Admin::UsersController#approve_vip as HTML
Parameters: {"authenticity_token"=>"qYrbaVH/cssY3VBYLw6Hd4wXl42Zz8OqkdHGGoITEeeWtbJ4ZOLOmJF/Jmpx70s9aaL5Yr0vFhqNV9kGHtILpA==", "user_id"=>"26"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 4], ["LIMIT", 1]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 26], ["LIMIT", 1]]
SQL (1.4ms) UPDATE "users" SET "is_vip" = 't' WHERE "users"."id" = ? [["id", 26]]
(0.0ms) begin transaction
(0.0ms) commit transaction
DEPRECATION WARNING: `redirect_to :back` is deprecated and will be removed from Rails 5.1. Please use `redirect_back(fallback_location: fallback_location)` where `fallback_location` represents the location to use if the request has no HTTP referer information. (called from approve_vip at /Users/a1/JDDstore/app/controllers/admin/users_controller.rb:26)
Redirected to http://localhost:3000/admin/users
Completed 302 Found in 6ms (ActiveRecord: 1.7ms)
Started POST "/admin/users/26/approve_vip" for ::1 at 2016-12-12 15:41:47 +0800
Processing by Admin::UsersController#approve_vip as HTML
Parameters: {"authenticity_token"=>"uYc9hdEZaYCgfhdmYK3XnyK2lcraPpHWfuXcQ5cRtLyGuFSU5ATV0yncYVQ+TBvVxwP7Jf7eRGZiY8NfC9Cu/w==", "user_id"=>"26"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 4], ["LIMIT", 1]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 26], ["LIMIT", 1]]
(0.0ms) begin transaction
(0.0ms) commit transaction
DEPRECATION WARNING: `redirect_to :back` is deprecated and will be removed from Rails 5.1. Please use `redirect_back(fallback_location: fallback_location)` where `fallback_location` represents the location to use if the request has no HTTP referer information. (called from approve_vip at /Users/a1/JDDstore/app/controllers/admin/users_controller.rb:26)
Redirected to http://localhost:3000/admin/users
Completed 302 Found in 4ms (ActiveRecord: 0.3ms)
And the code in controller is
def approve_vip
#user = User.find(params[:user_id])
#user.is_vip=true
#user.save
redirect_to :back
end
Can you tell me why it not change the role?
If you want to know more informatian, please let me know. Thank you very much for helping me.
It looks you have some model callback (may be before_save) which is restricting to update the records.
You can use update_column or update_columns to bypass the callbacks/validations and directly make a update query to your db.
def approve_vip
#user = User.find(params[:user_id])
#user.update_columns(is_vip: true)
redirect_to :back
end
You need to read error's message. Probably the user's validation is failed.
def approv!
update_attributes!(is_vip: true)
end
This code give you exception with the error's message.
I'm trying to do what I think should be simple: do a simple edit on a single text string field with the default update action. But it just doesn't seem to work, despite many attempts and alterations.
There are no errors and the flash message responds successfully, but information isn't saved to the database at all:
routes.rb
resources :interviews do
resources :invitations do
put :accept
end
end
views/invitations/edit.html.haml
= simple_form_for [#interview, #invitation] do |f|
= f.error_notification
= f.input :testing
= f.submit 'Edit Invitstion', :class => 'button small'
controllers/invitations_controller.rb
def update
#invitation = Invitation.find(params[:id])
#interview = Interview.find(params[:interview_id])
#invitation.update_attributes(invitation_params)
if #invitation.update_attributes(invitation_params)
redirect_to edit_interview_invitation_path(#interview, #invitation), notice: "Your profile has been successfully updated."
else
render action: "edit"
end
end
private
def invitation_params
params.permit(:user_id, :interview_id, :invitation_id, :session_time, :workflow_state, :testing)
end
And here's the log:
Started PATCH "/interviews/3/invitations/7" for ::1 at 2016-05-15 19:01:52 +0800
Processing by InvitationsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"o0U5t0yPN0aE2er+DWK0uxqRGyp4ywfdSrEfvwiSQ3UUaOnr3Fd0raFs1IUqVzizKoqxRU0DDpmvysntB9fdhQ==", "invitation"=>{"interview_id"=>"3", "workflow_state"=>"invited", "session_time"=>"", "testing"=>"testtesttest"}, "commit"=>"Edit Invitstion", "interview_id"=>"3", "id"=>"7"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 7]]
Invitation Load (0.2ms) SELECT "invitations".* FROM "invitations" WHERE "invitations"."id" = $1 LIMIT 1 [["id", 7]]
Role Load (0.2ms) SELECT "roles".* FROM "roles" WHERE "roles"."id" = $1 LIMIT 1 [["id", 3]]
Interview Load (0.2ms) SELECT "interviews".* FROM "interviews" WHERE "interviews"."id" = $1 ORDER BY created_at DESC LIMIT 1 [["id", 3]]
CACHE (0.0ms) SELECT "invitations".* FROM "invitations" WHERE "invitations"."id" = $1 LIMIT 1 [["id", "7"]]
CACHE (0.0ms) SELECT "interviews".* FROM "interviews" WHERE "interviews"."id" = $1 ORDER BY created_at DESC LIMIT 1 [["id", "3"]]
Unpermitted parameters: utf8, _method, authenticity_token, invitation, commit, id
(0.1ms) BEGIN
Invitation Exists (0.4ms) SELECT 1 AS one FROM "invitations" WHERE ("invitations"."user_id" = 3 AND "invitations"."id" != 7 AND "invitations"."interview_id" = 3) LIMIT 1
(0.1ms) COMMIT
Redirected to http://localhost:3000/interviews/3/invitations/7/edit
Completed 302 Found in 12ms (ActiveRecord: 1.6ms)
Started GET "/interviews/3/invitations/7/edit" for ::1 at 2016-05-15 19:01:52 +0800
Processing by InvitationsController#edit as HTML
Parameters: {"interview_id"=>"3", "id"=>"7"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 7]]
Invitation Load (0.3ms) SELECT "invitations".* FROM "invitations" WHERE "invitations"."id" = $1 LIMIT 1 [["id", 7]]
Role Load (0.2ms) SELECT "roles".* FROM "roles" WHERE "roles"."id" = $1 LIMIT 1 [["id", 3]]
Interview Load (0.2ms) SELECT "interviews".* FROM "interviews" WHERE "interviews"."id" = $1 ORDER BY created_at DESC LIMIT 1 [["id", 3]]
Rendered invitations/edit.html.haml within layouts/application (6.1ms)
Completed 200 OK in 48ms (Views: 39.1ms | ActiveRecord: 1.6ms)
Check the format of your params object in your logs. Your invitation params are being passed within the params["invitation"] key, yet you're whitelisting and updating your object based on the params in the root params hash.
Also note that your logs are reporting that you're trying to update your invitation with unpermitted params:
Unpermitted parameters: utf8, _method, authenticity_token, invitation, commit, id
You can fix this by simply updating your invitation_params to use params[:invitation] rather than params like so:
def invitation_params
params.require(:invitation).permit(:user_id, :interview_id, :invitation_id, :session_time, :workflow_state, :testing)
end
Also, you might want to consider raising an error if you're trying to update a parameter that's not whitelisted to prevent these sorts of issues in the future.
In your rails config:
config.action_controller.action_on_unpermitted_parameters = :raise
Here is my problem:
I'm using Devise's guest_user, that contains a logging_in method to transfer guest_user parameters to the registered user when he logs in. So in my case, the user has_many periods, dependent: :destroy, so here is the logging_in method:
def logging_in
guest_periods = guest_user.periods.all
guest_periods.each do |p|
p.user_id = current_user.id
p.save!
end
current_user.latest_entry = guest_user.latest_entry
current_user.is_in_zone = guest_user.is_in_zone
current_user.save
end
However, when a guest_user logs in, his periods gets destroyed instead of being transfered. Here is the log:
Started GET "/" for ::1 at 2015-05-11 00:18:03 +0300
Processing by WelcomeController#index as HTML
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 24]]
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 23]]
Period Load (0.3ms) SELECT "periods".* FROM "periods" WHERE "periods"."user_id" = $1 [["user_id", 23]]
(0.2ms) BEGIN
CACHE (0.0ms) SELECT "periods".* FROM "periods" WHERE "periods"."user_id" = $1 [["user_id", 23]]
SQL (0.8ms) UPDATE "periods" SET "user_id" = $1, "updated_at" = $2 WHERE "periods"."id" = $3 [["user_id", 24], ["updated_at", "2015-05-10 21:18:03.863162"], ["id", 170]]
(0.9ms) COMMIT
(0.2ms) BEGIN
SQL (2.1ms) UPDATE "users" SET "is_in_zone" = $1, "latest_entry" = $2, "updated_at" = $3 WHERE "users"."id" = $4 [["is_in_zone", "t"], ["latest_entry", "2015-05-04"], ["updated_at", "2015-05-10 21:18:03.875572"], ["id", 24]]
(15.8ms) COMMIT
(0.5ms) BEGIN
SQL (0.3ms) DELETE FROM "periods" WHERE "periods"."id" = $1 [["id", 170]]
SQL (0.7ms) DELETE FROM "users" WHERE "users"."id" = $1 [["id", 23]]
(1.2ms) COMMIT
So we can see that the transfer is done, but then in the end, the periods are destroyed anyway. They should not be, as they are not belonging to the user to be destroyed any more.
Why is it happening?
Even though Period#user_id has changed, guest_user.periods is still loaded in memory and is what gets destroyed when you destroy the guest user. If you guest_user.reload, its associations will clear out and it becomes safe to destroy. You could also guest_user.periods(true) to force reload of just the periods.
Another option is:
guest_user.periods.update_all(user_id: current_user.id)
This executes a single query to perform the update, which will be nice if there are a lot of periods, and also doesn't load the guest_user.periods association, so it will load fresh during the destroy and find the correct empty set.