Rails 3: Auto-populating a table upon new user creation with Devise - ruby-on-rails

I'm using devise to handle my users and as part of my application each user has their own 'todo' list. I'm trying to create 5 items in a new list every time a new user is created (so they have some sample data).
What is the best way to do this? I've looked at migrations and seed.rb but these don't seem to meet my needs.
Any help would be really appreciated!
Cheers!

use :after_create hook.
class User < ActiveRecord::Base
after_create :populate_todo
private
def populate_todo
# do your stuff here
end
end

Related

Rails - allows user to do some actions only few times within certain timeframe

I have Rails api, and I use it to upload photos from the mobile app. Is there a way to set something like a timer from Rails back-end to let say allow one user only upload twice in an hour and/or another user twice in a day? I am a little puzzled with logic of how it can work from the back-end since I don't wanna do it from the front-end. Any advice is appreciated. Thanks!
Simple. Just check how many records the user has created in the alloted time frame. Lets say you have the following associations:
class User
has_many :photos
end
class Photo
belongs_to :user
end
And a current_user method that returns the authenticated user.
To query based on a time frame you use a range:
def create
#photo = current_user.photos.new(photo_params)
unless current_user.photos.where(created_at: (1.hour.ago..Time.now)).count <= 2
#photo.errors.add(:base, 'You have reached the upload limit')
end
# ...
end
Later when you refactor you can move this into the model as a custom validation.

how to run a one-time database change on a single user

I have Customer and each customer has_many Properties. Customers belong to a Company.
I'm trying to add a certain Property to each one of a single Company's Customers. I only want this change to happen once.
I'm thinking about using a migration but it doesn't seem right to create a migration for a change that I only ever want to happen once, and only on one of my users.
Is there a right way to do this?
You can just use rails console.
In rails c:
Company.where(conditions).last.customers.each do |customer|
customer.properties << Property.where(condition)
customer.save!
end
Validation
Depending on how you're changing the Customer model, I'd include a simple vaidation on the before_update callback to see if the attribute is populated or not:
#app/models/Customer.rb
class Customer < ActiveRecord::Base
before_update :is_valid?
private
def is_valid?
return if self.attribute.present?
end
end
This will basically check if the model has the attribute populated. If it does, it means you'll then be able to update it, else it will break
--
Strong_Params
An alternative will be to set the strong_params so that the attribute you want to remain constant will not be changed when you update / create the element:
#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
...
private
def strong_params
params.require(:model).permit(:only, :attributes, :to, :update)
end
end
It would be much more helpful if you explained the context as to why you need this type of functionality - that will give people the ability to create a real solution, instead of proposing ideas

Adding default role to Devise user model

While trying to add roles-based authentication (using CanCan and Devise) to my project I found that there are two ways to save roles: the first one is "Has and Belongs_to" way and the second one is just saving role in new field in users table.
So, the question is, how can I define deafult user role in the first way and which way should I choose to define deafult role in the second one (setting default role in migration or editing Devise's user controller?)
Also, should I use this method or is it better to use gem instead?
P.S. I've already read Tony Amoyal's tutorial but didn't found an answer there.
If I understood the question correctly, here is what worked for me: Ruby on rails, cancan and default role assignment
Simply add the following into /models/user.rb to assign default role on signup:
after_create :default_role
private
def default_role
self.roles << Role.where(:name => 'User').first
end
This situation described in Rails AntiPatterns book: http://railsantipatterns.com/
Short answer is: use field in users table, set default role using migrations. This way is much simpler. You should not use complex solution just because it can possibly better suit your future needs.
You can do the following in user.rb:
after_initialize :set_default_role
private
def set_default_role
self.role ||= :user
end
A very easy users role solution can be implemented using this gem: https://github.com/platform45/easy_roles

In my rails app, how can I automatically attach a userID when a new product is created?

I have a rails app, with two separate DB tables, users and products. A user has_many products, and a product belongs_to a user.
When I create a product, I want it to automatically add the user_id to the user_id database column in the products table. What changes to my mvc do I need to make to ensure that the correct user_id is added when a new product is created?
You can scope the creation of the new product through the user.
For example, instead of this:
Product.create(params[:product])
you do this:
current_user.products.create(params[:product])
where "current_user" is the user creating the product.
Just as a suggestion, you may want to go back and accept the answers to some of your previous questions, which will improve your response rate and increase the likelihood someone will answer your questions in the future.
There are a few ways to do this, one approach:
Create current user function
class ApplicationController < ActionController::Base
private
# Finds the User with the ID stored in the session with the key
# :current_user_id This is a common way to handle user login in
# a Rails application; logging in sets the session value and
# logging out removes it.
def current_user
#_current_user ||= session[:current_user_id] &&
User.find_by_id(session[:current_user_id])
end
end
http://guides.rubyonrails.org/action_controller_overview.html#session
Make sure to be cognizant of security concerns. A gem like Devise can also help.
Add to products controller
class ProductsController < ApplicationController
def create
current_user.products.create! params[:product] # make sure attr_accessible is setup on products
end
end

Ruby on Rails 3 - create an instance of one model from another model

I have the following problem, but first I will make some assumptions
The example is just to explain my problem in an easy way
The tables models are not related
I have two tables (models) Users an Emails
Users
id
name
email
Emails
id
account
So, the idea is every time I create a user, I want to create an instance of Email, where Emails.account = Users.email
I tried using callback
def after_create
Email.create!(:account => user.email)
end
But it didn't work.
Is there another way to achieve this?
You are almost there, except you don't need to reference a 'user' variable in your after_create because you are in the User model.
Try the following:
class User < ActiveRecord::Base
after_create :create_email
def create_email
Email.create!(:account => email)
end
end

Resources