Pass Account ID to New User During Sign Up - ruby-on-rails

Currenntly, my application is designed using Devise for authentication. I have it so when the first user signs up, an account is created in an Accounts table and the account_id is passed to the User table. I also have it set so that each time a new account is created that user is tagged as an admin. Finally, I have it working where the admin can create new users.
My problem is that at the time the new users are created I need to have these users be assigned the same account_id as the admin to tie the users together. I can do this if I add an account_id field on the form and have the admin manually enter it. What I want to have is that this is automated in the background.
I tried many varieties without success. This is one of the unsuccesful attempts where I put the following in the user.rb
before_save :add_account_id_from_parent
def add_account_id_from_parent
return true unless self.users.present?
self.users.update_attribute(:account_id, 1)
end
I used the number "1" just to see if I could get anything automated and placed in that field.
Like I said manually everything works, but I want it so the acocunt_id is automatically added during sign up based on the admins account_id.

I'm a bit confused why you are calling self.users. If I understand correctly, you want to assign account_id to 1 after a new user is created (as a test). You can do that like this:
before_save :add_account_id_from_parent
def add_account_id_from_parent
self.account_id = 1
end
You don't need to actually update the record since this is assigned before save, and save will write the new value to the db.
Again I might be missing something, if so please clarify.
UPDATE:
If you're validating that account is present, you'll need to change the callback to a before_validation instead of before_save, like so:
before_validation :add_account_id_from_parent

Related

Attaching existing order (order.email) to create an account, Devise?

This is the scenario I would like to accomplish:
User creates an order (enters email into order table).
User is sent order confirmation email with link to sign up.
If User decides to sign up, it will connect to the account.
What would it take to accomplish this?
I'm a bit mixed up because the Order is already created and wouldn't have a current_user for the order model to attach to the User model. How would I then have it so the order.buyer_id (which is used for the current_user of the User who creates the Order) then gets associated with the to-be-signed up User who just created the order. How could I somehow embed this information in the "sign up" link that gets sent? To somehow say "if this email signs up and is confirmed, become the buyer_id for said order"?
Also, is this good practice?
Other option:
Or should I just have a "email" and "password" field when checking out where the User field get sent ahead of the payment token so the order attaches to the current_user?
Does anyone have other ideas or what I should do?
Other than this, the only thing I'm currently doing is a simple "sign up before ordering if you want to save your orders"
Email is unique for each user so after user signed up and account created you can run a small query where you assign created user to orders. It can be accomplished in the model
class User < ActiveRecord::Base
after_create :connect_orders
...
def connect_orders
Order.where(email: self.email).updated_all(buyer_id: self.id)
end
end

Rails 5 access profile data anywhere in session without querying database each time

I've a user profile (with name, logo, about_me) which is created after user creation(using Devise). Profile table uses user_id as Primary key.
Now I want that whenever the user creates/updates a post, while filling in form some details are taken from profile, so profile data or #profile be available in post form as I cannot expose my model in form.
To set post.myname attribute in create and #update I'm doing this:
#myprofile = Profile.find_by_user_id(current_user)
write_attribute(:myname, #myprofile.name)
I read from various sources but what's the best solution of the 4 given and if anyone can back with easy code as I do not want to do something extensive? Thanks in advance.
1)Form Hidden fields - Like get the profile data as above in hash in #edit and then pass through form and access fields in #update but that way we will pass each field separately. Can one #myprofile be passed?
2)Session - I feel if profile data is stored in a session and someone updates profile then updated data won't be available in that session.So not sure if it is plausible.
3)Caching - easy way to do that?
4)polymorphic profile---tried it but I didnot get relevant example. I was stuck with what to put as profileable id and type and how to use them in the code.
If your Profile and User models have a one-to-one relationship with each other, the simplest solution is to remove the Profile model altogether and move its fields into the User model.
Devise already queries the database to obtain the current_user object. So, your example would like this:
write_attribute(:myname, current_user.name)
Which wouldn't hit the database (after Devise has retrieved the current_user object).
If you're forced to keep the Profile model, in looking at your four scenarios ...
You could use a session variable. Something like:
session[:profile_name] ||= #myprofile.name
This would go in a controller action.
The trick here is that you will want to redefine the each relevant session variable if the profile gets updated. And because you don't have access to the session in the model, you'd be best to perform that action in the controller. So, not pretty, but it could work.
You could also use low-level caching, and save the profile relationship on the user. In general, you could have a method like this in your user model:
def profile_cached
Rails.cache.fetch(['Profile', profile.id]) do
profile
end
end
Here, too, you will have to know when to expire the cache. The benefit of this approach is that you can put this code in the model, which means you can hook its expiration in a callback.
Read more about this in Caching with Rails.
I would avoid hidden fields and I'm not sure how a polymorphic relationship would solve you not hitting the database. So, #2 and #3 are options, but if you can combine the two models into one, that should simplify it.

Rails adding row to DB through admin approval

I am making an application in Rails and I have Devise about to be included for users management. I have an index page where all the database rows are in with CRUD ability which is all good.
The functionality I'm after is that if a user wants to add a new row, they can go through and 'add' it but before it gets actually added, the request goes through to an admin, then the admin can hit 'approve' and then the row gets added.
The issue is me trying to get around the fact that the program would 'hold' an action of adding a row and the admin would approve it, then the program would let that action apply.
Thanks.
Instead of going through the hassle of preventing saving the row to the DB (you'd have to cancel the saving in a before_create callback but keep the data somewhere anyway and pass them to admin for approval somehow), I'd do a much simpler approach.
Add another column to the table, boolean column named e.g. approved and by default show only all approved rows in the listing. When a user creates a row, save it with approved = false and let admins access these unapproved rows and approve them simply by setting approved = true or delete them if approval is denied.
Also consider creating a DB index for this column for performance reasons.

Rails Security - Enforcing ownership at the model level

I recently coded up a 'friend' capability with my website. The way it works is if a user wants to 'friend' another user, sending a request creates a user_connection record with the original user set at the user_id and the requested user set as the contact_id. If the other user accepts the request, then another user_connection record will be made, with the user_id and contact_id reversed. If both user_connections exist, then the two users are considered friends. This currently gives each user access to any buildings shared between the two users.
I was wondering if there was some way I could enforce my user_connection model to make sure that whoever is creating the record gets set as the user_id. Otherwise it seems that someone could spoof the user_connection create request to make themself a contact of whomever they want, and then could spoof building shares using the same methodology. Are there any built in methods to prevent this?
My first thought was to have an initializer that always set the user_id to the current_user's id, but it appears that current_user is outside of the context of the model.
Don't allow user_id to be provided as a parameter, using strong params.
So, you could create the relation like that:
#friendship = current_user.friendships.new(contact_id: other_user.id)
Also make sure you provide the correct condition for current_user.
That's it... user_id is implied but never provided.

Generate unique usernames in rails

How can I generate unique usernames based on a format. So for example the first user signs up. The username for him is AAA001 the second user signs up the username will be AAA002, and it keeps incrementing like that. How can I set it up so even if two users click sign up at the same time the database just sends them each a unique username. This is gonna be done on RoR.
Thank you in advance
you can generate the username in the after_safe hook of the model and save! again in a transaction (to prevent race conditions) and use the DB-ID of the already saved user to generate the username
You need to use database transactions.
Here is an example:
ActiveRecord::Base.transaction do
#code goes here
end
This will ensure that the code inside the transaction is blocking.

Resources