When a user creates an accounts, the code should allow that user to register a user account through Devise and then create an account, plus a company.
The code should redirect to a wizard setup using the wicked gem.
Users have roles (rolify) and are authorized with Cancancan.
The tables are setup using has_many :through association. This seems to work.
The models are as follows:
user
has_many :accounts_users
has_many :accounts, through: :accounts_users, dependent: :destroy
has_one :company, through: :accounts, dependent: :destroy
users_account
belongs_to :account
belongs_to :user
account
resourcify
has_many :accounts_users
has_many :users, through: :accounts_users, dependent: :destroy
has_one :company
company
belongs_to :account
The create account controller is the following:
def new
#account = Account.new
end
def create
if !current_user.present?
build_resource(sign_in_params)
account = Account.find_or_create_by(org_name: params[:user] [:account])
else
#account = current_user.accounts.create!(account_params)
end
# create a default account and company
#account.save!
current_user.add_role 'owner'
current_account = current_user.accounts.first
# create a company associated with the newly created account
if current_account.companies.empty?
company = current_account.companies.create(company_name: params[:org_name])
else
company = current_account.companies.first
end
resource.update(current_company: company.id)
respond_to do |format|
if #account.save
# redirect to the relevant wizard
format.html { redirect_to after_account_path(:add_account), notice: 'Account was successfully created.' }
else
format.html { render action: 'new' }
format.json { render json: #account.errors, status: :unprocessable_entity }
end
end
end
EDITED VERSION
def create
#account = Account.create(account_params.except(:company))
#account.save!
respond_to do |format|
if #account.save
create_company
format.html { redirect_to #account, notice: 'Account was successfully created.' }
format.json { render :show, status: :created, location: #account }
else
format.html { render :new }
format.json { render json: #account.errors, status: :unprocessable_entity }
end
end
end
def create_company
current_user.add_role 'owner'
current_account = current_user.accounts.first
if current_account.company.nil?
current_account.build_company(company_name: params[:org_name])
#company.save!
else
company = current_account.company
end
resource.update(current_company: company.id)
end
included in Application helper:
def current_account
current_user.accounts.first
end
def current_company
current_user.accounts.first.companies.first
end
it redirects (unexpected) to displaying (show) the Company data right after creation, I receive a nil / no method error.
the index and how controller are:
before_action :set_company, only: [:show, :edit, :update, :destroy,
:new]
def index; end
def show
#company = Company.find_by(id: params[:id])
end
def set_company
#company = current_account.company
end
This seems to work. Editing the Company is a challenge but should get there.
Any advices to get to a better code is welcome
Have you thought about just making the front end handle the case where #name isn't set yet?
<=% #company&.name %>
or
<=% #company.name || "Unknown" %>
Related
I have a User object and an Orgs object that are associated through a HABTM join table. I want to send an email to the users when the Orgs object is updated AND the Org.approved value is set to true. I have an approved boolean on the Org.
I think I've gotten most of the way there but I need help with the step of actually sending the email.
Here's my code
class OrgMailer < ApplicationMailer
default from: 'myemail#example.co'
def org_approved(user, org)
#user = user
#orgs = User.orgs.all
#url = 'http://example.com/login'
mail(to: #user.email, subject: 'Your listing has been approved.')
end
end
User.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_and_belongs_to_many :orgs, join_table: :orgs_users
end
Org.rb
class Org < ApplicationRecord
has_and_belongs_to_many :users, join_table: :orgs_users
# after_update :send_approved_listing_email, only: [:update]
attachment :company_image
def send_approved_listing_email
OrgMailer.org_approved(i).deliver_now if org.approved === true
end
end
UPDATED: ADDED ORG_CONTROLLER
I've edited my code to look like the answer below but am now getting a new error: uninitialized constant Org::OrgsUser
It's caused when I hit the #org.users << #user line in the create action.
If I delete this line, I'm able to create an org but it's not associating properly.
org_controller.rb
class OrgsController < ApplicationController
before_action :set_org, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
def index
#orgs = Org.all
#tags = ActsAsTaggableOn::Tag.all
end
def show
end
def new
#org = Org.new
end
def contest
end
def edit
end
def create
#user = current_user
#org = Org.new(org_params)
#org.users << #user
respond_to do |format|
if #org.save
format.html { redirect_to thankyou_path, notice: 'Your listing was successfully created. Our team will approve your listing after review.' }
format.json { render :show, status: :created, location: #org }
else
format.html { render :new }
format.json { render json: #org.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #org.update(org_params)
format.html { redirect_to #org, notice: 'Listing was successfully updated.' }
format.json { render :show, status: :ok, location: #org }
else
format.html { render :edit }
format.json { render json: #org.errors, status: :unprocessable_entity }
end
end
end
def destroy
#org.destroy
respond_to do |format|
format.html { redirect_to orgs_url, notice: 'Listing was successfully destroyed.' }
format.json { head :no_content }
end
end
def tagged
if params[:tag].present?
#orgs = Org.tagged_with(params[:tag])
else
#orgs = Org.postall
end
end
private
def set_org
#org = Org.find(params[:id])
end
def org_params
params.require(:org).permit(:twitter, :linkedin, :facebook, :name, :offer, :offercode, :url, :descrption, :category, :approved, :company_image, :tag_list => [])
end
end
I'm using active admin for my admin panel and have a batch action to update any selected orgs and approve them. I think what I'm missing is that in the send_approved_listing_email method I need to iterate through the orgs and email each user when the org is approved.
Right now nothing happens on update so I'm sure I'm not doing this correctly. What am I missing? How should I write this?
I would create a model for the join table rather than using habtm. That way you can use a callback when the join object is saved:
class User < ApplicationRecord
has_many :orgs_users
has_many :orgs, through: :orgs_users
end
class Org < ApplicationRecord
has_many :orgs_users
has_many :users, through: :orgs_users
end
class OrgsUsers < ApplicationRecord
belongs_to :org
belongs_to :user
after_create :send_approved_listing_email
def send_approved_listing_email
OrgMailer.org_approved(user, org).deliver_now if org.approved === true
end
end
In my Rails 4 app, there are 5 models:
class User < ActiveRecord::Base
has_many :administrations
has_many :calendars, through: :administrations
end
class Calendar < ActiveRecord::Base
has_many :administrations
has_many :users, through: :administrations
has_many :posts
end
class Administration < ActiveRecord::Base
belongs_to :user
belongs_to :calendar
end
class Post < ActiveRecord::Base
belongs_to :calendar
end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
I implemented authentication with Devise (so we have access to current_user).
Now, I am trying to implement authorization with Pundit (first timer).
Following the documentation, I installed the gem and ran the rails g pundit:install generator.
Then, I created a CalendarPolicy, as follows:
class CalendarPolicy < ApplicationPolicy
attr_reader :user, :calendar
def initialize(user, calendar)
#user = user
#calendar = calendar
end
def index?
user.owner? || user.editor? || user.viewer?
end
def show?
user.owner? || user.editor? || user.viewer?
end
def update?
user.owner? || user.editor?
end
def edit?
user.owner? || user.editor?
end
def destroy?
user.owner?
end
end
I also updated my User model with the following methods:
def owner?
Administration.find_by(user_id: params[:user_id], calendar_id: params[:calendar_id]).role == "Owner"
end
def editor?
Administration.find_by(user_id: params[:user_id], calendar_id: params[:calendar_id]).role == "Editor"
end
def viewer?
Administration.find_by(user_id: params[:user_id], calendar_id: params[:calendar_id]).role == "Viewer"
end
I updated my CalendarsController actions with authorize #calendar, as follows:
def index
#user = current_user
#calendars = #user.calendars.all
end
# GET /calendars/1
# GET /calendars/1.json
def show
#user = current_user
#calendar = #user.calendars.find(params[:id])
authorize #calendar
end
# GET /calendars/new
def new
#user = current_user
#calendar = #user.calendars.new
authorize #calendar
end
# GET /calendars/1/edit
def edit
#user = current_user
authorize #calendar
end
# POST /calendars
# POST /calendars.json
def create
#user = current_user
#calendar = #user.calendars.create(calendar_params)
authorize #calendar
respond_to do |format|
if #calendar.save
current_user.set_default_role(#calendar.id, 'Owner')
format.html { redirect_to calendar_path(#calendar), notice: 'Calendar was successfully created.' }
format.json { render :show, status: :created, location: #calendar }
else
format.html { render :new }
format.json { render json: #calendar.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /calendars/1
# PATCH/PUT /calendars/1.json
def update
#user = current_user
#calendar = Calendar.find(params[:id])
authorize #calendar
respond_to do |format|
if #calendar.update(calendar_params)
format.html { redirect_to calendar_path(#calendar), notice: 'Calendar was successfully updated.' }
format.json { render :show, status: :ok, location: #calendar }
else
format.html { render :edit }
format.json { render json: #calendar.errors, status: :unprocessable_entity }
end
end
end
# DELETE /calendars/1
# DELETE /calendars/1.json
def destroy
#user = current_user
#calendar.destroy
authorize #calendar
respond_to do |format|
format.html { redirect_to calendars_url, notice: 'Calendar was successfully destroyed.' }
format.json { head :no_content }
end
end
And I included after_action :verify_authorized, :except => :index in my ApplicationController.
Now, when I log in, I can access http://localhost:3000/calendars/ but when I try to visit http://localhost:3000/calendars/new, I get the following error:
Pundit::NotAuthorizedError in CalendarsController#new
not allowed to new? this #<Calendar id: nil, name: nil, created_at: nil, updated_at: nil>
#user = current_user
#calendar = #user.calendars.new
authorize #calendar
end
Obviously, I must have done something wrong.
Problem: I can't figure out what.
Any idea?
You don't have access to the params in the model unless you pass them through. You should pass the calendar to the model instance function and you already have access to the user.
user.editor?(calendar)
def editor?(calendar)
Administration.find_by(user_id: self.id, calendar_id: calendar.id).role == "Editor"
end
The problem was that I had not defined a create action in the CalendarPolicy.
Since the CalendarPolicy inherits from the ApplicationPolicy — CalendarPolicy < ApplicationPolicy — and the create action in the ApplicationPolicy is set to false by default, I was getting an error.
Simply adding the following code to CalendarPolicy fixed the problem:
def create?
true
end
Bonus tip: there is no need to add a new action to CalendarPolicy since we already have the following code in ApplicationPolicy:
def new?
create?
end
I followed the instructions here to create a model Lesson in which there is a student and a teacher (both of the model User) and also a lesson start date.
#Lesson Controller
class Lesson < ActiveRecord::Base
belongs_to :student, class_name => 'User'
belongs_to :teacher, class_name => 'User'
end
#User Controller
class User < ActiveRecord::Base
has_many :lessons_to_attend, :class_name => 'Lesson', :foreign_key => 'student_id'
has_many :lessons_to_teach, :class_name => 'Lesson', :foreign_key => 'teacher_id'
end
The migration went smoothly and so on a page I try to query the student's lessons for tomorrow:
<% #date = 1.day.from_now %>
<%= #date.strftime("%A")%></br>
<%= #date.strftime("%-d/%-m/%y")%>
<% #user.lessons_to_attend.each do |l| %>
Lesson
<% end %>
But when I navigate to this page I get the error Uninitialized constant error Lesson::User
What did I miss out? I'll include the User controller in case something needs to be added in there.
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /users
# GET /users.json
def index
#users = User.all
end
# GET /users/1
# GET /users/1.json
def show
#user = User.find(params[:id])
end
# GET /users/new
def new
#user = User.new
end
# GET /users/1/edit
def edit
end
# POST /users
# POST /users.json
def create
#user = User.new(user_params)
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: #user }
else
format.html { render :new }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: #user }
else
format.html { render :edit }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
#user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
#user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params[:user]
end
end
Two things:
belongs_to :student, class_name => 'User'
belongs_to :teacher, class_name => 'User'
Syntax error on class_name. That should either be :class_name => 'User' or class_name: 'User'.
The other thing is that I think you need to set your inverse_of on both sides of the association.
class Lesson < ActiveRecord::Base
belongs_to :student, class_name: 'User', inverse_of: :lessons_to_attend
belongs_to :teacher, class_name: 'User', inverse_of: :lessons_to_teach
end
class User < ActiveRecord::Base
has_many :lessons_to_attend, class_name: 'Lesson', foreign_key: 'student_id', inverse_of: :student
has_many :lessons_to_teach, class_name: 'Lesson', foreign_key: 'teacher_id', inverse_of: :teacher
end
I have one model, User, and then 2 other models: Editor and Administrator associated with the user model via a polymorphic association, so I want to have 2 type of users, and they will have different fields, but I need them to share certain features (like sending messages between both).
I thus need to keep the user ids in one table, users, and the other data in other tables, but I want that when a user signs up they first create the account and then the profile according to the type of profile they did pick.
model/user.rb
class User < ActiveRecord::Base
belongs_to :profilable, :polymorphic => true
end
model/administrator.rb
class Administrator < ActiveRecord::Base
has_one :user, :as => :profilable
end
model/Editor.rb
class Editor < ActiveRecord::Base
attr_accessor :iduser
has_one :user, :as => :profilable
end
controllers/user.rb
def create
#user = User.new(params[:user])
respond_to do |format|
if #user.save
if params[:tipo] == "editor"
format.html {redirect_to new_editor_path(:iduser => #user.id)}
else
format.html { redirect_to new_administrator_path(#user) }
end
# format.json { render json: #user, status: :created, location: #user }
else
format.html { render action: "new" }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
controllers/editor.rb
def new
#editor = Editor.new
#editor.iduser = params[:iduser]
respond_to do |format|
format.html # new.html.erb
format.json { render json: #editor }
end
end
def create
id = params[:iduser]
#user = User.find(id)
#editor = Editor.new(params[:editor])
#editor.user = #user
respond_to do |format|
if #editor.save
format.html { redirect_to #editor, notice: 'Editor was successfully created.' }
format.json { render json: #editor, status: :created, location: #editor }
else
format.html { render action: "new" }
format.json { render json: #editor.errors, status: :unprocessable_entity }
end
end
end
views/editor/_form.html.erb
<div class="field">
<%= f.label :bio %><br />
<%= f.text_area :bio %>
<%= f.hidden_field :iduser%>
</div>
routes.rb
Orbit::Application.routes.draw do
resources :administrators
resources :editors
resources :users
When someone creates a new user they have to pic "Editor" or "Administrator" with a radio button, then using that parameter, the code will create an Editor or Administrator profile.
I am not sure if i have the association right, because it should be "User has a profile (editor/administrator)" but in this case is "Profile (administrator/editor) has a user".
The question:
Is the association right for what I want to accomplish?
How could I pass the user to the new editor method?
The way i have it right now is not working, and as I said, the association doesn't seem to be right.
Thanks for the time
Try and swap the association,
The user will have an administrator profile, and administrator profile will belong_to the user.
Administrator(:user_id, :other_attributes)
Editor(:user_id, :other_attributes)
So that,
class Administrator < ActiveRecord::Base
belongs_to :user
end
class Editor < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_one :administrator
has_one :editor
end
Hi Guys I have a Relationships in Mongoid and I can not add current_user to this relation for get the user that create the deal. A relation with 3 model.
I have three models user.rb, house.rb and deal.rb
user.rb Relationships (devise model)
# Relationships
has_many :houses, dependent: :destroy
has_many :deals, dependent: :destroy
key :title
house.rb
# Relationships
belongs_to :user
embeds_many :deals
deal.rb
# Relationships
embedded_in :house, :inverse_of => :deals
belongs_to :user
In my routes.rb
resources :houses do
resources :deals
end
In my houses_controller.rb in my create method I get current_user for each house of this side:
def create
##house = House.new(params[:house])
#house = current_user.houses.new(params[:house])
respond_to do |format|
if #house.save
format.html { redirect_to #house, notice: 'House was successfully created.' }
format.json { render json: #house, status: :created, location: #house }
else
format.html { render action: "new" }
format.json { render json: #house.errors, status: :unprocessable_entity }
end
end
end
In my deals_controller.rb I have the created method this:
def create
#house = House.find_by_slug(params[:house_id])
#user = User.find(:user_id)
#deal = #house.deals.create!(params[:deal])
redirect_to #house, :notice => "Comment created!"
end
How I can add to this last method create, the current_user that created the deal?
You can simply add these two lines to the create action:
#deal.user=current_user
#deal.save
And I would also suggest you not to use create! instead you should use .new and .save like in the scaffolded create actions! ;)