I'm trying to do a test send using
u = User.invite!({:email => "myemail#live.com", :name => "John Doe"}, User.find(1))
Why is Devise Invitable trying to insert into tables companies and company_roles with wierd/wrong values when I'm actually expecting only the user table to be updated.
This behaviour causes a ROLLBACK since the invite does not have the correct values to update these tables.
I only want to save stuff like company_role in the callback after the user has accepted an invite. How do I do this in the callback function and how do I access the initial values sent by the invite.
For example, can I do this?
u = #referrer.invite!({
email: params[:email],
title: params[:title],
first_name: params[:first_name],
last_name: params[:last_name],
website: #website,
company_id: #company,
country: #country,
}, #referrer)
And then later retrieve some of the values in the accept callback using this in the User model?
after_invitation_accepted :email_invited_by
def email_invited_by
# ...
end
Related
I need to create an object with the associated item all in the step of creation.
Although I have tried creating first, and then second, this gives problems in the way that if the second fails, then I get with the first part half done.
Relationship one user has many companies
I mean something like
user = User.create!(
email: prospect.email,
first_name: prospect.first_name,
last_name: prospect.last_name,
#birthdate:prospect.user_birthday,
id_number: prospect.id_number,
phone: prospect.phone,
address: prospect.address,
password: prospect.id_number,
password_confirmation: prospect.id_number,
company = user.companies.create(
name: prospect.vat_company_name,
plan: prospect.plan,
address: prospect.address,
description: prospect.company_description,
email: prospect.email,
phone: prospect.phone,
network_id: prospect.network_id
)
current_company_id: company.id
)
which of course fails because maybe it can't be done directly.
I have tried build instead of create, but same result.
I also know that second create will fail because the first object doesn't exist yet.
How is the best way?
You can create them both separately and wrap them in a transaction:
ActiveRecord::Base.transaction do
user = User.create!(...)
company = Company.create!(...)
end
This way if one of them fails, the other doesn't end up being committed to the database.
If you are talking about separate instance storage then using a db transaction lock is the way to go forward as mentioned by Danial. But if you only need to create an associated record of active record then you can do with Active Record only. It would make sure that both records are saved.
user = User.new
email: prospect.email,
first_name: prospect.first_name,
last_name: prospect.last_name,
#birthdate:prospect.user_birthday,
id_number: prospect.id_number,
phone: prospect.phone,
address: prospect.address,
password: prospect.id_number,
password_confirmation: prospect.id_number
user.build_current_company
name: prospect.vat_company_name,
plan: prospect.plan,
address: prospect.address,
description: prospect.company_description,
email: prospect.email,
phone: prospect.phone,
network_id: prospect.network_id
user.save!
This will create both user and it's current company.
(I am taking an assumption that you have belongs_to :current_company,class_name: 'Company' in user.rb)
I am trying to update a hash that is being made when a csv is uploaded by a user, so that it saves the added key/value pair to the db.
How can I update the hash being made in the create_by_location method with the method check_enable_recordings
user model
before_save :check_enable_recordings
def check_enable_recordings
x = tenant.enable_recording_extensions
Rails.logger.debug("check if true #{x}" )
if x
user = User.new(
recorded: "1"
)
end
end
def self.create_by_location(location,hash)
user = User.new(
first_name: hash[:firstname],
last_name: hash[:lastname],
email: hash[:email],
)
end
Perhaps you're looking for something like:
before_save :check_enable_recordings
def check_enable_recordings
self.recorded = 1 if tenant.enable_recording_extensions
end
def self.create_by_location(location,hash)
user = User.new(
first_name: hash[:firstname],
last_name: hash[:lastname],
email: hash[:email],
)
end
BTW, you don't seem to use the location argument anywhere. Maybe you're not showing us all the code.
Also, if you have control over the construction of the hash argument, you should probably change firstname to first_name and lastname to last_name so you can just do:
def self.create_by_location(location,hash)
user = User.new(hash)
end
Assume I have the following class:
class User < ActiveRecord::Base
has_many :addresses
end
And I'm initializing the following record:
user = User.new(first_name: "John", last_name: "Doe", address_ids: [1, 2, 3])
There already exists a convenient method provided by Rails to retrieve the attributes of a model's record:
user.attributes # => {first_name: "John", last_name: "Doe"}
However, I also need to get a hash that contains the address_ids as well, that is:
user.attributes_with_has_many_associations
# => {first_name: "John", last_name: "Doe", address_ids: [1, 2, 3]}
I'm looking for a general way to do this on any given record(i.e. does not involve reflecting the associations to pull the attributes and end up the polluting the model itself, after all I'm looking for a way to do this purely for testing purposes) or at least to have a method isolated in the test code.
Not sure if there is a Rails method but you could define it yourself.
def attributes_with_has_many_associations
attributes.merge(
self
.class
.reflect_on_all_associations(:has_many)
.map(&:plural_name)
.map { |as| { as.to_sym => self.send(as) } }
.reduce(&:merge)
)
end
I'm struggling to understand the relationship that owner = create(:user, device_token: device_token) has to owner: {device_token: device_token}, I usually use user_id for this association.
2. What is the device_token method in the controller is doing.
describe 'POST /v1/events' do
it 'saves the address, lat, lon, name, and started_at date' do
date = Time.zone.now
device_token = '123abcd456xyz'
owner = create(:user, device_token: device_token)
post '/v1/events', {
address: '123 Example St.',
ended_at: date,
lat: 1.0,
lon: 1.0,
name: 'Fun Place!!',
started_at: date,
owner: {
device_token: device_token
}
}.to_json, { 'Content-Type' => 'application/json' }
event = Event.last
expect(response_json).to eq({ 'id' => event.id })
expect(event.address).to eq '123 Example St.'
expect(event.ended_at.to_i).to eq date.to_i
expect(event.lat).to eq 1.0
expect(event.lon).to eq 1.0
expect(event.name).to eq 'Fun Place!!'
expect(event.started_at.to_i).to eq date.to_i
expect(event.owner).to eq owner
end
end
Controller Code:
def create
#event = Event.new(event_params)
if #event.save
render
end
end
private
def event_params
{
address: params[:address],
ended_at: params[:ended_at],
lat: params[:lat],
lon: params[:lon],
name: params[:name],
started_at: params[:started_at],
owner: user
}
end
def user
User.find_or_create_by(device_token: device_token)
end
def device_token
params[:owner].try(:[], :device_token)
end
end
There's a number of ways you can identify uniquely identify a record in a database. Using the id field is the most common - but if you've got another way to uniquely identify a user, then you can use that, too. Normally, you don't show a user what their ID number is in the database. But, if you want to give them a way to uniquely identify themselves, you could create another field which is unique for each user - such as a membership_number or similar. It seems like in your case, device_token is a field that uniquely identifies a user.
So, your database cares about the user_id field - that's what it uses to tie an Event to a specific User (aka, the owner). If your users knew their id, then they could pass in that, rather than their device_token, and everything would be fine. But they don't know it.
So, they pass in their devise_token. You use that to fetch the user from the database, and then you know that user's id. Then, you can store that user's id in the user_id field of your Event model.
def user
User.find_or_create_by(device_token: device_token)
end
This method is the one that gets a user based on a devise_token. And then this method:
def event_params
{
address: params[:address],
ended_at: params[:ended_at],
lat: params[:lat],
lon: params[:lon],
name: params[:name],
started_at: params[:started_at],
owner: user
}
end
In particular, the line: owner: user calls that method above. From that point, Rails handles it under the hood and makes sure your user_id is set correctly.
UPDATE AFTER YOUR COMMENT:
device_token is being passed in as a parameter. It is also the name of a field in the User model. So, a single row in the user table might look like this:
id: 24, first_name: fred, last_name: flintstone, device_token: 123abc, address: bedrock, etc.
the method:
def user
User.find_or_create_by(device_token: device_token)
end
is saying: go to the User's table in the database, try to find a User which has a device_token that has the value that was passed in as a parameter, and if we can't find one, then create one.
So in this line: User.find_or_create_by(device_token: device_token), the first reference to device_token is the key of a hash, and it refers to the field called device_token in your User model.
The second reference to device_token is a call to this method:
def device_token
params[:owner].try(:[], :device_token)
end
which fetches the device_token from the parameters passed in. This method basically says: Look in the params hash at the value inside the owner key. See if the owner key contains a device_token. If it does, return that device_token, and if it doesn't return nil. It does this using the try method, which you can read more about here: http://apidock.com/rails/Object/try
I want to use this function from mongoid:
person.update_attributes(first_name: "Jean", last_name: "Zorg")
But I want to pass in all the attributes from another variable. How do I do that?
Edit: Thanks everyone for your reply. I'm new to ruby so at first I thought I just made a silly mistake with this. The bug was in a completely different place, the correct code, for your enjoyment:
def twitter
# Scenarios:
# 1. Player is already signed in with his fb account:
# we link the accounts and update the information.
# 2. Player is new: we create the account.
# 3. Player is old: we update the player's information.
# login with a safe write.
puts "twitter"
twitter_details = {
twitter_name: env["omniauth.auth"]['user_info']['name'],
twitter_nick: env["omniauth.auth"]['user_info']['nickname'],
twitter_uid: env["omniauth.auth"]['uid']
}
if player_signed_in?
#player = Player.find(current_player['_id'])
else
#player = Player.first(conditions: {twitter_uid: env['omniauth.auth']['uid']})
end
if #player.nil?
#player = Player.create!(twitter_details)
else
#player.update_attributes(twitter_details)
end
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Twitter"
sign_in_and_redirect #player, :event => :authentication
end
The update_attributes method takes a Hash argument so if you have a Hash, h, with just :first_name and :last_name keys then:
person.update_attributes(h)
If your Hash has more keys then you can use slice to pull out just the ones you want:
person.update_attributes(h.slice(:first_name, :last_name))
if you look at the source code of Mongoid, you'll see the definition of update_attributes in the file
.rvm/gems/ruby-1.9.2-p0/gems/mongoid-2.3.1/lib/mongoid/persistence.rb
# Update the document attributes in the datbase.
#
# #example Update the document's attributes
# document.update_attributes(:title => "Sir")
#
# #param [ Hash ] attributes The attributes to update.
#
# #return [ true, false ] True if validation passed, false if not.
def update_attributes(attributes = {})
write_attributes(attributes); save
end
It takes a Hash -- that means you can use a Hash as the variable that's passed in.
e.g.
my_attrs = {first_name: "Jean", last_name: "Zorg"}
person.update_attributes( my_attrs )
What's happening in the update_attributes method and, indeed, across the Rails platform is variables get put into a hash internally, when necessary.
So the following are equivalent:
person.update_attributes(first_name: "Jean", last_name: "Zorg")
person.update_attributes({first_name: "Jean", last_name: "Zorg"})
person.update_attributes(name_hash)
Where name_hash is:
name_hash = {first_name: "Jean", last_name: "Zorg"}