Devise does not update all the custom fields in the User model - ruby-on-rails

I have a User model with following attributes, seller and estado (status).
t.string "estado", default: "pending"
t.boolean "seller", default: false
I have some validations for the User model:
validates :seller, default: false
validates :estado, inclusion: { in: %w(Accepted),
message: "Status application: %{value}" }
I am tweeking devise, (in controller registrations, method create)trying to update these fields because of other conditions. For the seller it works, for the estado it does not
Here is the prove:
[4] pry(#<Users::RegistrationsController>)> resource.estado = "Accepted"
=> "Accepted"
[5] pry(#<Users::RegistrationsController>)> resource
=> #<User id: nil, email: "vendedor1#mail.com", created_at: nil, updated_at: nil, shop_id: nil, seller: true, first_name: nil, last_name: nil, birthday: nil, nationality: nil, document_type: nil, document_number: nil, expiring_date: nil, estado: "pending", admin: false>
[6] pry(#<Users::RegistrationsController>)> resource.seller = false
=> false
[7] pry(#<Users::RegistrationsController>)> resource
=> #<User id: nil, email: "vendedor1#mail.com", created_at: nil, updated_at: nil, shop_id: nil, seller: false, first_name: nil, last_name: nil, birthday: nil, nationality: nil, document_type: nil, document_number: nil, expiring_date: nil, estado: "pending", admin: false>
Why is not updating the value of estado? I see it in the console, but when I inspect resource, it's still pending.
I could allow the attributes commenting out this, as the first comment suggests:
# protected
# If you have extra params to permit, append them to the sanitizer.
# def configure_sign_up_params
# devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute])
# end
# If you have extra params to permit, append them to the sanitizer.
# def configure_account_update_params
# devise_parameter_sanitizer.permit(:account_update, keys: [:attribute])
# end

Related

ActiveRecord::AssociationTypeMismatch: User(#35560) expected, got ... which is an instance of User(#22700)

I've been getting intermittent errors while seeding with rails. I'm hoping someone can help provide some insight into the different types of the User class.
The error in full:
ActiveRecord::AssociationTypeMismatch: User(#35560) expected, got #<User id: "bedc7c4e-cdd2-4ea1-a7ee-4e6642467fba", email: "phil#email.domain", jti: "7376cf41-7f88-407d-8365-1e311d946b88", ios_device_token: nil, fcm_device_token: nil, first_name: "Phil", last_name: "6", phone_number: nil, date_of_birth: nil, super_user: true, created_at: "2023-02-08 08:16:37.559974000 +0000", updated_at: "2023-02-08 08:16:37.559974000 +0000"> which is an instance of User(#22700)
The code which causes it:
user = User.new(
first_name: 'Phil',
last_name: '6',
email: 'phil#email.domain',
super_user: true,
password: 'test1234'
)
user.skip_confirmation!
user.save!
organisation = Organisation.find_by_name('Team')
Membership.create!(
user:,
organisation:,
verified: true,
verified_at: now,
organisation_admin: true,
shift_admin: true,
email: 'phil.6#group.com',
email_confirmed: true,
category: organisation.categories.find_by_name('Developer')
)
organisation = Organisation.find_by_name('Test Org')
membership = Membership.create!(
user:,
organisation:,
verified: true,
verified_at: now,
email: 'phil#testorg.com',
email_confirmed: true
)
If I pause execution before the error I can see that user == User.first is false despite User.first and user being these two lines, which are visually identical:
#<User id: "6ce62b08-cf4c-4bfa-878a-02a1ed889c69", email: "phil#email.domain", jti: "710948b6-5f4f-40ea-ab9f-df8e3b1219c3", ios_device_token: nil, fcm_device_token: nil, first_name: "Phil", last_name: "6", phone_number: nil, date_of_birth: nil, super_user: true, created_at: "2023-02-08 08:17:06.024800000 +0000", updated_at: "2023-02-08 08:17:06.024800000 +0000">
#<User id: "6ce62b08-cf4c-4bfa-878a-02a1ed889c69", email: "phil#email.domain", jti: "710948b6-5f4f-40ea-ab9f-df8e3b1219c3", ios_device_token: nil, fcm_device_token: nil, first_name: "Phil", last_name: "6", phone_number: nil, date_of_birth: nil, super_user: true, created_at: "2023-02-08 08:17:06.024800000 +0000", updated_at: "2023-02-08 08:17:06.024800000 +0000">
It's the same thing if I compare user.class and User.first.class, they look the same but a comparison evaluates to false.
Am I doing something to mutate the local variable?
What you should be doing here is to create an assocation:
class User < ApplicationRecord
has_many :memberships
end
Then you create the memberships through that assocation instead:
user = User.create!(
first_name: 'Phil',
last_name: '6',
email: 'phil#email.domain',
super_user: true,
password: 'test1234',
confirmed_at: Time.current # the easy way to skip Devise::Confirmable
)
# make sure you use the bang method so that you're not just getting a nil
organisation = Organisation.find_by_name!('Test Org')
user.memberships.create!(
organisation: organisation,
verified: true,
verified_at: now,
organisation_admin: true,
shift_admin: true,
email: 'phil.6#group.com',
email_confirmed: true,
category: organisation.categories.find_by_name!('Developer')
)

Ruby on Rails - as_json remove some attributes

I have a response ready with some attributes. However, I dont want some of them to get passed on to the response. How do I do that? I think I need to use except somehow.
The :only and :except options can be used to limit the attributes
included, and work similar to the attributes method.
user.as_json(only: [:id, :name])
# => { "id" => 1, "name" => "Konata Izumi" }
user.as_json(except: [:id, :created_at, :age])
# => { "name" => "Konata Izumi", "awesome" => true }
You can use except parameter of as_json like so:
2.5.0 :001 > {foo: 1, bar: 2, baz: 3}.as_json(except: [:baz])
=> {"foo"=>1, "bar"=>2}
You can use only or except for your use case.
Something like below should work:
#<Address id: nil,
address1: nil,
address2: nil,
city_name: nil,
zipcode: nil,
phone: nil,
state_id: nil,
country_id: nil,
created_at: nil,
updated_at: nil,
address_type: nil,
latitude: nil,
longitude: nil,
city_id: nil,
locality: nil>
json = address.as_json(only: %i[id
address1
address2
locality
city_id
zipcode
address_type
latitude
longitude],
methods: [:city_slug]) # yes, you can use methods as attributes also

ActiveRecord + Pry confusion

This is confusing me no end.
In a rake task, I am saving new records on the DailyScore model with the following code:
def save_record_as_daily_score_object(data)
#ds = DailyScore.where(date: data[:date]).first_or_create!
#ds.update!(data)
binding.pry
end
The pry output is as follows:
[10] pry(main)> data
=> {:date=>"2015-09-02",
:mail=>-0.6,
:times=>-7.1,
:telegraph=>-2.2,
:guardian=>-4.0,
:express=>-0.1,
:independent=>-3.2,
:average=>-3.4}
[11] pry(main)> #ds
=> #<DailyScore:0x000001098121a8
id: 4975,
mail: nil,
telegraph: nil,
times: nil,
average: nil,
guardian: nil,
independent: nil,
express: nil,
date: nil,
created_at: 2016-05-16 13:10:03 UTC,
updated_at: 2016-05-16 13:10:03 UTC>
[12] pry(main)> #ds.average
=> -3.4
[13] pry(main)> #ds.date
=> "2015-09-02"
[14] pry(main)> #ds.persisted?
=> true
[15] pry(main)> DailyScore.last
=> #<DailyScore:0x000001086810d8
id: 4975,
mail: nil,
telegraph: nil,
times: nil,
average: nil,
guardian: nil,
independent: nil,
express: nil,
date: nil,
created_at: 2016-05-16 13:10:03 UTC,
updated_at: 2016-05-16 13:10:03 UTC>
[16] pry(main)> DailyScore.last.average
=> nil
What is going on here? Why can't Pry access my variable attributes? And is the record actually being saved or not?
UPDATE:
Checking in the console, the behaviour is the same if I simply create a new object. I'm using the Padrino framework, and a Postgres db.
2.0.0 :001 > ds = DailyScore.new(date:"2016-01-01")
=> #<DailyScore id: nil, mail: nil, telegraph: nil, times: nil, average: nil, guardian: nil, independent: nil, express: nil, date: nil, created_at: nil, updated_at: nil>
2.0.0 :002 > ds.date
=> "2016-01-01"
2.0.0 :003 > ds
=> #<DailyScore id: nil, mail: nil, telegraph: nil, times: nil, average: nil, guardian: nil, independent: nil, express: nil, date: nil, created_at: nil, updated_at: nil>
Is it a problem with the model? Here is the original migration:
006_create_daily_scores.rb
class CreateDailyScores < ActiveRecord::Migration
def self.up
create_table :daily_scores do |t|
t.float :average
t.datetime :date
t.float :express
t.float :independent
t.float :guardian
t.float :telegraph
t.float :mail
t.float :times
t.timestamps
end
end
def self.down
drop_table :daily_scores
end
end
Have now added another column day:date - using :date instead of :datetime - to check if it was a quirk with :datetime, but behaviour is the same.
This happens because you called attr_accessor in your model with your model attributes, which overrode default accessors provided by Rails (the accessors are called by update and new methods). Note this doc, for reference, if you do want to override accessors one day.
Removing attr_accessor from your model will do the trick!

Callbacks in aasm gem and ActionMailer

Im learning ruby on rails and have a trouble with aasm callbacks and actionmailer.
I have a hotels model. Heres a code:
class Hotel < ActiveRecord::Base
include AASM
scope :approved_hotels, -> { where(aasm_state: "approved") }
has_many :comments
belongs_to :user, :counter_cache => true
has_many :ratings
belongs_to :address
aasm do
state :pending, initial: true
state :approved
state :rejected
event :approve, :after => :send_email do
transitions from: :pending, to: :approved
end
event :reject, :after => :send_email do
transitions from: :pending, to: :rejected
end
end
def send_email
end
end
As you see user has to get email when state of the hotel he added was changed. Heres what i wrote but its not THE solution cos user gets emails every time admin updates hotel with "pending" state.
class HotelsController < ApplicationController
before_filter :authenticate_user!, except: [:index, :show, :top5hotels]
def update
#hotel = Hotel.find(params[:id])
if #hotel.aasm_state == "pending"
#hotel.aasm_state = params[:state]
UserMailer.changed_state_email(current_user, #hotel.name,
#hotel.aasm_state).deliver
end
if #hotel.update_attributes!(params[:hotel])
redirect_to admin_hotel_path(#hotel), notice: "Hotel was successfully updated."
else
render "edit"
end
end
end
So i think i need to use callback but i dont know how to call
UserMailer.changed_state_email(current_user, #hotel.name,
#hotel.aasm_state).deliver
from the model.
I tried
UserMailer.changed_state_email(User.find(:id), Hotel.find(:name),
Hotel.find(aasm_state)).deliver
but that doesnt work.
Im really out of options and looking for any help.
Thanks!
UPDATE 1:
Thank to Amit Sharma! I`ve made these changes and now getting
NoMethodError: undefined method `email' for nil:NilClass
Looks like user object Im passing to changed_state_email() method is nill but I have no idea why.
Here is my mailer file aswell:
class UserMailer < ActionMailer::Base
default from: "localhost"
# Send email to user when hotels state change
def changed_state_email(user, hotel_name, current_state)
mail(to: user.email, subject: 'State of your hotel '+hotel_name+'has been
changed to '+current_state)
end
end
Here is a result of puts "====#{self.inspect}":
====#<Hotel id: nil, name: "CoolName", breakfast: nil, room_description: nil, price_for_room: 34, star_rating: 3, user_id: nil, address_id: nil, created_at: nil, updated_at: nil, average_rating: nil, photo_file_name: nil, photo_content_type: nil, photo_file_size: nil, photo_updated_at: nil, aasm_state: "approved">
F.====#
F.====#
UPDATE 2:
It returns user object. Output from the console:
1.9.3-p551 :006 > h = Hotel.find(1)
Hotel Load (0.4ms) SELECT "hotels".* FROM "hotels" WHERE "hotels"."id" = ? LIMIT 1 [["id", 1]]
=> #<Hotel id: 1, name: "QWERTYUI", breakfast: nil, room_description: nil, price_for_room: 44, star_rating: 4, user_id: 2, address_id: nil, created_at: "2015-05-30 22:55:01", updated_at: "2015-05-30 22:55:01", average_rating: nil, photo_file_name: nil, photo_content_type: nil, photo_file_size: nil, photo_updated_at: nil, aasm_state: "pending">
1.9.3-p551 :007 > h
=> #<Hotel id: 1, name: "QWERTYUI", breakfast: nil, room_description: nil, price_for_room: 44, star_rating: 4, user_id: 2, address_id: nil, created_at: "2015-05-30 22:55:01", updated_at: "2015-05-30 22:55:01", average_rating: nil, photo_file_name: nil, photo_content_type: nil, photo_file_size: nil, photo_updated_at: nil, aasm_state: "pending">
1.9.3-p551 :008 > h.user
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 2]]
=> #<User id: 2, name: "qwerty", email: "qweqweqweqwe#qwe.com", encrypted_password: "$2a$10$FG5xXb/9wYLcdsCrfJtuDOTsslyY8p.m0qkbP4a5OEvJ...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, admin: false, created_at: "2015-05-30 22:54:14", updated_at: "2015-05-30 22:54:14", comments_count: 0, hotels_count: 1>
You can Try this. I hope this will help you.
In Hotels Controller.
class HotelsController < ApplicationController
before_filter :authenticate_user!, except: [:index, :show, :top5hotels]
def update
#hotel = Hotel.find(params[:id])
if #hotel.pending?
if params[:state] == "approved"
#hotel.approved!
elsif params[:state] == "rejected"
#hotel.rejected!
end
end
if #hotel.update_attributes!(params[:hotel])
redirect_to admin_hotel_path(#hotel), notice: "Hotel was successfully updated."
else
render "edit"
end
end
end
In Hotel model.
def send_email
user = self.user
puts "====#{self.inspect}===#{user.inspect}"
UserMailer.changed_state_email(user, self.name,
self.aasm_state).deliver
end
Please revert back to me if you face any issue.

Rename image using associated model - Paperclip

Code
In my image model:
has_attached_file :pic
before_post_process :rename_pic
before_save ->{ p 'before_save ----------------' }
after_post_process ->{ p 'after_post_process --------------' }
def rename_pic
p 'en imagen'
p self
p 'en imagen'
end
In service that has many images:
# don't use accepts_nested_attributes_for
before_save :create_images
attr_accessor :images_attributes
def create_images
# images_attributes example value: { "0"=> {img_attrs}, "1" => {img_attrs1} }
images_attributes.all? do |k, image_attrs|
if image_attrs.delete(:_destroy) == "false"
p 'asd'
image = Image.new image_attrs.merge(service_id: id)
p image.service
p image.service_id
image.save
end
end
end
This is the output I get:
"asd"
"en imagen"
#<Image id: nil, service_id: nil, pic_file_name: "Screen_Shot_2013-04-07_at_5.18.03_PM.png", pic_content_type: "image/png", pic_file_size: 16041, pic_updated_at: "2013-07-30 22:58:46", created_at: nil, updated_at: nil, user_id: nil>
"en imagen"
G"after_post_process --------------"
#<Service id: 427, event_id: nil, min_capacity: nil, max_capacity: nil, price: #<BigDecimal:7fb6e9d73d48,'0.0',9(18)>, image_path: nil, name: "Super Franks", desc: "zxc", created_at: "2013-05-12 19:01:54", updated_at: "2013-07-30 19:32:48", address: "pasadena", longitude: 77.225, latitude: 28.6353, gmaps: true, city: "san francisco", state: "california", country_id: "472", tags: "Banquet", created_by: 22, avg_rating: #<BigDecimal:7fb6efdbcf10,'0.0',9(18)>, views: 27, zip_code: "", address2: "", price_unit: "", category_id: 3, featured: true, publish: true, slug: "banquet-super-franks", discount: nil, currency_code: "USD", video_url: "http://www.youtube.com/watch?v=A3pIrBZQJvE", short_description: "">
427
"before_save ----------------"
Problem
When calling
image = Image.new image_attrs.merge(service_id: id)
Paperclips seems to start processing, and then set service_id.
So when I try to use service inside rename_pic service is nil.
Any ideas on how to handle this?
This solved my problem, I changed:
before_post_process :rename_pic
to:
before_create :rename_pic
and this is rename_pic, for the record:
def rename_pic
extension = File.extname(pic_file_name).downcase
self.pic.instance_write :file_name,
"#{service.hyphenated_for_seo}#{extension}"
end
where service has_many images, and image belongs_to service.
Be carefull with the fix of #juanpastas, because if you change before_post_process to before_create, it will only run when you create your image, and not when you update it. To have the callback still run on update, do this:
class YourImage
has_attached_file :pic
# use both callbacks
before_create :rename_pic
before_post_process :rename_pic
def rename_pic
# assotiated_object is the association used to get pic_file_name
return if self.assotiated_object.nil?
extension = File.extname(pic_file_name).downcase
self.pic.instance_write :file_name,
"#{service.hyphenated_for_seo}#{extension}"
end
end

Resources