I'm using the pundit gem in order to give permissions to three different users(Admin, seller, viewer). Currently I got everything working, admin has access to everything, seller to his own products and viewer can just view the products.
The only glitch I'm having is that I would like the non signed_up/signed_in users to be able to view the products via search results. Right now non sign_up/signed_in users can see the search results but don't have access to the show view.
Here is the setup I have:
class ItemPolicy < ApplicationPolicy
attr_reader :item
def initialize(user, record)
super(user, record)
#user = user
#item = record
end
def update?
#user.is_a?(Admin) ? item.all : #user.items
end
def index?
#user.is_a?(Admin) ? item.all : #user.items
end
def show?
#user.is_a?(Admin) ? item.all : #user.items
end
def create?
#user.is_a?(Admin) ? item.all : #user.items
end
def new?
#user.is_a?(Admin) ? item.all : #user.items
end
def edit?
#user.is_a?(Admin) ? item.all : #user.items
end
def destroy?
#user.is_a?(Admin) ? item.all : #user.items
end
class Scope < Struct.new(:user, :scope)
def resolve
if user.is_a?(Admin)
scope.where(:parent_id => nil)
elsif user.is_a?(Seller)
scope.where(:id => user.items)
end
end
def show?
return true if user.is_a?(Admin)
return true if user.seller_id == seller.id && user.is_a?(Seller)
false
end
end
end
the controller:
class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update, :destroy]
def index
authorize Item
#items = policy_scope(Item)
end
def search
if params[:term]
#items = Item.search(params[:term]).order("created_at DESC")
else
#items = []
end
end
def show
#comments = Comment.where(item_id: #item).order("created_at DESC")
#items = policy_scope(Item).find(params[:id])
authorize #item
end
def new
#item = Item.new
authorize #item
#categories = Category.order(:name)
end
def edit
authorize #item
#categories = Category.order(:name)
end
def create
#item = Item.new(item_params)
authorize #item
respond_to do |format|
if #item.save
format.html { redirect_to #item, notice: 'Item was successfully created.' }
format.json { render :show, status: :created, location: #item }
else
format.html { render :new }
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
def update
authorize #item
respond_to do |format|
if #item.update(item_params)
format.html { redirect_to #item, notice: 'Item was successfully updated.' }
format.json { render :show, status: :ok, location: #item }
else
format.html { render :edit }
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
def destroy
authorize #item
#item.destroy
respond_to do |format|
format.html { redirect_to items_url, notice: 'Item was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_item
#item = Item.find(params[:id])
authorize #item
end
def item_params
params.require(:item).permit(:title, :description, :image, :price, :category_id)
end
end
application_contoller.rb
class ApplicationController < ActionController::Base
include Pundit
protect_from_forgery prepend: true
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
def pundit_user
current_seller || current_admin || current_viewer
end
private
def user_not_authorized(exception)
policy_name = exception.policy.class.to_s.underscore
flash[:warning] = t "#{policy_name}.#{exception.query}", scope: "pundit", default: :default
redirect_to(request.referrer || root_path)
end
end
Update 1
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
raise Pundit::NotAuthorizedError, "must be logged in" unless user
#user = user
#record = record
end
def index?
true # anybody can view
end
def show?
true # anybody can view
end
def search?
index?
end
def new?
create?
end
def edit?
update?
end
def destroy?
update?
end
private
# don't repeat yourself
def admin?
user.is_a?(Admin)
end
def seller?
user.is_a?(Seller)
end
end
class ItemPolicy < ApplicationPolicy
attr_reader :item
class Scope < Struct.new(:user, :scope)
def resolve
if admin?
scope.where(parent_id: nil)
elsif seller?
# avoids a query for user.items
scope.where(seller: user)
end
end
end
def initialize(user, record)
super(user, record)
#user = user
#item = record
end
def update?
admin? || is_owner?
end
def create?
# just guessing here
admin? || seller?
end
private
def is_owner?
# or whatever the association between the item and its owner is
item.seller == user
end
end
You are confusing scopes and the authorization methods in Pundit. The new?, show? etc. methods should return a boolean indicating if the user is allowed to perform the action at all.
To allow unauthorized users to perform an action you simply return true.
Scopes are used to narrow down which records the user has access to. They only have a resolve method.
class ApplicationPolicy
# ...
private
# don't repeat yourself
def admin?
user.is_a?(Admin)
end
def seller?
user.is_a?(Seller)
end
end
class ItemPolicy < ApplicationPolicy
attr_reader :item
class Scope < Struct.new(:user, :scope)
def resolve
if admin?
scope.where(parent_id: nil)
elsif seller?
# avoids a query for user.items
scope.where(seller: user)
end
end
end
def initialize(user, record)
super(user, record)
#user = user
#item = record
end
def update?
admin? || is_owner?
end
def index?
true # anybody can view
end
def show?
true # anybody can view
end
def search?
index?
end
def create?
# just guessing here
admin? || seller?
end
def new?
create?
end
def edit?
update?
end
def destroy?
update?
end
private
def is_owner?
# or whatever the association between the item and its owner is
item.seller == user
end
end
Instead of repeating yourself (the conditions) you can shortcut many of the actions since the permissions for editing for example is the same as updating. You can even do this in the ApplicationPolicy so that you don't have to repeat it in each policy class:
class ApplicationPolicy
# ...
def index?
true # anybody can view
end
def show?
true # anybody can view
end
def search?
index?
end
def new?
create?
end
def edit?
update?
end
def destroy?
update?
end
private
# don't repeat yourself
def admin?
user.is_a?(Admin)
end
def seller?
user.is_a?(Seller)
end
end
class ItemPolicy < ApplicationPolicy
attr_reader :item
class Scope < Struct.new(:user, :scope)
def resolve
if admin?
scope.where(parent_id: nil)
elsif seller?
# avoids a query for user.items
scope.where(seller: user)
end
end
end
def initialize(user, record)
super(user, record)
#user = user
#item = record
end
def update?
admin? || is_owner?
end
def create?
# just guessing here
admin? || seller?
end
private
def is_owner?
# or whatever the association between the item and its owner is
item.seller == user
end
end
You are also authorizing the user twice at many places in your controller as it is as already performed by the set_item callback:
class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update, :destroy]
def index
authorize Item
#items = policy_scope(Item)
end
def search
if params[:term]
#items = Item.search(params[:term]).order("created_at DESC")
else
#items = Item.none # Don't use [] as #items.none? for example would blow up.
end
end
def show
#comments = Comment.where(item_id: #item).order("created_at DESC")
authorize #item
end
def new
#item = authorize(Item.new)
#categories = Category.order(:name)
end
def edit
#categories = Category.order(:name)
end
def create
#item = authorize(Item.new(item_params))
respond_to do |format|
if #item.save
format.html { redirect_to #item, notice: 'Item was successfully created.' }
format.json { render :show, status: :created, location: #item }
else
format.html { render :new }
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #item.update(item_params)
format.html { redirect_to #item, notice: 'Item was successfully updated.' }
format.json { render :show, status: :ok, location: #item }
else
format.html { render :edit }
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
def destroy
#item.destroy
respond_to do |format|
format.html { redirect_to items_url, notice: 'Item was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_item
#item = authorize( Item.find(params[:id]) )
end
def item_params
params.require(:item).permit(:title, :description, :image, :price, :category_id)
end
end
Related
I am a newbie when it comes to RubyOnRails. Recently while working with the gem pundit I encountered a problem. Pundit during function sort? authorization does not see the logged in user that is #user = nill. I don't know what the problem is because other authorizations with the same syntax works for example edit? I am uploading the code below:
lesson_controler.rb
class LessonsController < ApplicationController
before_action :set_lesson, only: [ :show, :edit, :update, :destroy ]
def sort
#course = Course.friendly.find(params[:course_id])
#lesson = Lesson.friendly.find(params[:lesson_id])
authorize #lesson
#lesson.update(lesson_params)
render body: nil
end
def index
#lessons = Lesson.all
end
def show
authorize #lesson
current_user.view_lesson(#lesson)
#lessons = #course.lessons
end
def new
#lesson = Lesson.new
#course = Course.friendly.find(params[:course_id])
end
def edit
authorize #lesson
end
def create
#lesson = Lesson.new(lesson_params)
#course = Course.friendly.find(params[:course_id])
#lesson.course_id = #course.id
authorize #lesson
respond_to do |format|
if #lesson.save
format.html { redirect_to course_lesson_path(#course,#lesson), notice: "Lesson was successfully created." }
format.json { render :show, status: :created, location: #lesson }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #lesson.errors, status: :unprocessable_entity }
end
end
end
def update
authorize #lesson
respond_to do |format|
if #lesson.update(lesson_params)
format.html { redirect_to course_lesson_path(#course,#lesson), notice: "Lesson was successfully updated." }
format.json { render :show, status: :ok, location: #lesson }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #lesson.errors, status: :unprocessable_entity }
end
end
end
def destroy
authorize #lesson
#lesson.destroy
respond_to do |format|
format.html { redirect_to course_path(#course), notice: "Lesson was successfully destroyed." }
format.json { head :no_content }
end
end
private
def set_lesson
#course = Course.friendly.find(params[:course_id])
#lesson = Lesson.friendly.find(params[:id])
end
def lesson_params
params.require(:lesson).permit(:title, :content, :row_order_position)
end
end
lesson_policy.rb:
class LessonPolicy < ApplicationPolicy
class Scope < Scope
def resolve
scope.all
end
end
def sort?
#record.course.user_id == #user.id
end
def edit?
#record.course.user_id == #user.id
end
def update?
#record.course.user_id == #user.id
end
def destroy?
#record.course.user_id == #user.id
end
def show?
#record.course.user_id == #user.id || #user&.has_role?(:admin) || #record.course.bought(#user) == false
end
def new?
#record.course.user_id == #user.id
end
def create?
#record.course.user_id == #user.id
end
end
Application_policy.rb:
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
#user = user
#record = record
end
def index?
false
end
def show?
false
end
def create?
false
end
def new?
create?
end
def update?
false
end
def edit?
update?
end
def destroy?
false
end
class Scope
def initialize(user, scope)
#user = user
#scope = scope
end
def resolve
scope.all
end
private
attr_reader :user, :scope
end
end
Console logs
How can I make a logged in user visible to pundit?
I would like to DRY my controller as I use some snippets/blocks of code many times inside the same controller (I have removed some as it was too long but this already gives an idea of the repetition). Here are the blocks I keep repeating :
#deal = search_deal
#next_deal = find_next_deal
#userdeal = find_or_create_userdeal_participation
#user_credits = calculate_user_credits_in_deal
I'm quite rookie and don't know how to do this but I feel this code should be factorized.
class DealsController < ApplicationController
before_filter :find_deal,
:only => [ :showcase ]
before_filter :ensure_canonical_deal_path!,
:only => [ :showcase ]
def showcase
# find appropriate deal
#deal = search_deal
respond_to do |format|
format.html # showcase.html.erb
format.json { render json: #deal }
end
end
def buy_stuff
#deal = search_deal
# bring 'next deal' url to the view
#next_deal = find_next_deal
# USER IS SIGNED-IN
if user_signed_in?
#userdeal = find_or_create_userdeal_participation
#user_credits = calculate_user_credits_in_deal
# if: user still has credits available
if #user_credits >= 1
#do this
respond_to do |format|
format.js
end
else
respond_to do |format|
# do that
end
end
# USER IS NOT SIGNED-IN
else
respond_to do |format|
format.js { render :template => "deals/call_to_sign_in.js.erb" }
end
end
end
def show_discounts
#deal = search_deal
respond_to do |format|
#do that
end
end
def pending_deals
#deal = search_deal
# bring 'next deal' url to the view
#next_deal = find_next_deal
if user_signed_in?
#userdeal = find_or_create_userdeal_participation
#user_credits = calculate_user_credits_in_deal
end
respond_to do |format|
#do this
end
end
def ask_question
#deal = search_deal
respond_to do |format|
#do that
end
end
protected
def ensure_canonical_deal_path!
if request.path != actual_deal_page_path(#deal)
redirect_to actual_deal_page_path(#deal, :format => params[:format]), :status => :moved_permanently
return false
end
end
private
# DRY file as this is used multiple times
# trick source - http://blog.rstankov.com/rails-anti-pattern-setting-view-variables-in-before-actions/
def search_deal
Deal.friendly.find(params[:id])
end
def find_or_create_userdeal_participation
UserDeal.where('user_id = ? AND deal_id = ?', current_user.id, #deal.id).take ||
UserDeal.create(user_id: current_user.id, deal_id: #deal.id)
end
def calculate_user_credits_in_deal
current_user.credit_nb + #userdeal.history
end
def find_next_deal
Deal.order_next_deal_at(#deal).next
end
end
I think the best way to just add before_filters for those methods where you are calling repeat code like:
before_filter :search_deal, :only => [:showcase, :buy_stuff, ...]
class DealsController < ApplicationController
before_filter :find_deal, only: [:showcase]
before_filter :ensure_canonical_deal_path!, only: [:showcase]
def showcase
search_deal
respond_to do |format|
format.html
format.json{render json: #deal}
end
end
def buy_stuff
search_deal
find_next_deal
if user_signed_in?
find_or_create_userdeal_participation
calculate_user_credits_in_deal
if #user_credits >= 1
respond_to(&:js)
else
respond_to{|format| }
end
else
respond_to{|format| format.js{render template: "deals/call_to_sign_in.js.erb"}}
end
end
def show_discounts
search_deal
respond_to{|format|}
end
def pending_deals
search_deal
find_next_deal
if user_signed_in?
find_or_create_userdeal_participation
calculate_user_credits_in_deal
end
respond_to{|format| }
end
def ask_question
search_deal
respond_to{|format| }
end
protected def ensure_canonical_deal_path!
if request.path != actual_deal_page_path(#deal)
redirect_to actual_deal_page_path(#deal, format: params[:format]), status: :moved_permanently
return false
end
end
private def search_deal
#deal = Deal.friendly.find(params[:id])
end
private def find_or_create_userdeal_participation
#user_deal =
UserDeal.where('user_id = ? AND deal_id = ?', current_user.id, #deal.id).take ||
UserDeal.create(user_id: current_user.id, deal_id: #deal.id)
end
private def calculate_user_credits_in_deal
#user_credits = current_user.credit_nb + #userdeal.history
end
private def find_next_deal
#next_deal = Deal.order_next_deal_at(#deal).next
end
end
In my app I have a commenting system that's largely based off of this railscast. Now in my models I'm changing the to_param to a random string so the id isn't in the url. But then that breaks commenting.
status.rb
class Status < ActiveRecord::Base
attr_accessible :content, :member_id, :document_attributes, :permalink
belongs_to :member
belongs_to :document
has_many :comments, as: :commentable, dependent: :destroy
before_create :make_it_permalink
accepts_nested_attributes_for :document
def to_param
permalink
end
private
def make_it_permalink
# this can create permalink with random 12 digit alphanumeric
self.permalink = SecureRandom.hex(12)
end
end
statuses_controller.rb
class StatusesController < ApplicationController
before_filter :authenticate_member!, only: [:index, :new, :create, :destroy]
before_filter :find_member
rescue_from ActiveRecord::RecordNotFound do
render file: 'public/404', status: 404, formats: [:html]
end
def index
#statuses = Status.order('created_at desc').page(params[:page]).per_page(21)
respond_to do |format|
format.html # index.html.erb
format.js
end
end
def show
#status = Status.find_by_permalink(params[:id])
#commentable = #status
#comments = #commentable.comments.order('created_at desc').page(params[:page]).per_page(15)
#comment = #commentable.comments.new
respond_to do |format|
format.html # show.html.erb
format.json { redirect_to profile_path(current_member) }
end
end
def new
#status = Status.new
#status.build_document
respond_to do |format|
format.html # new.html.erb
format.json { render json: #status }
format.js
end
end
def create
#status = current_member.statuses.new(params[:status])
respond_to do |format|
if #status.save
#activity = current_member.create_activity(#status, 'created')
format.html { redirect_to :back }
format.json
format.js
else
format.html { redirect_to profile_path(current_member), alert: 'Post wasn\'t created. Please try again and ensure image attchments are under 10Mbs.' }
format.json { render json: #status.errors, status: :unprocessable_entity }
format.js
end
end
end
def destroy
#status = current_member.statuses.find(params[:id])
#activity = Activity.find_by_targetable_id(params[:id])
#commentable = #status
#comments = #commentable.comments
if #activity
#activity.destroy
end
if #comments
#comments.destroy
end
#status.destroy
respond_to do |format|
format.html { redirect_to profile_path(current_member) }
format.json { head :no_content }
end
end
private
def find_member
#member = Member.find_by_user_name(params[:user_name])
end
def find_status
#status = current_member.statuses.find_by_permalink(params[:id])
end
end
comments_controller.rb
class CommentsController < ApplicationController
before_filter :authenticate_member!
before_filter :load_commentable
before_filter :find_member
def index
redirect_to root_path
end
def new
#comment = #commentable.comments.new
end
def create
#comment = #commentable.comments.new(params[:comment])
#comments = #commentable.comments.order('created_at desc').page(params[:page]).per_page(15)
#comment.member = current_member
respond_to do |format|
if #comment.save
format.html { redirect_to :back }
format.json
format.js
else
format.html { redirect_to :back }
format.json
format.js
end
end
end
def destroy
#comment = Comment.find(params[:id])
respond_to do |format|
if #comment.member == current_member || #commentable.member == current_member
#comment.destroy
format.html { redirect_to :back }
format.json
format.js
else
format.html { redirect_to :back, alert: 'You can\'t delete this comment.' }
format.json
format.js
end
end
end
private
# def load_commentable
# resource, id = request.path.split('/')[1,2] # photos/1/
# #commentable = resource.singularize.classify.constantize.find(id) # Photo.find(1)
# end
# alternative option:
def load_commentable
klass = [Status, Medium, Project, Event, Listing].detect { |c| params["#{c.name.underscore}_id"] }
#commentable = klass.find(params["#{klass.name.underscore}_id"])
end
#def load_commentable
# #commentable = params[:commentable_type].camelize.constantize.find(params[:commentable_id])
#end
def find_member
#member = Member.find_by_user_name(params[:user_name])
end
end
The problem lies in the load_commentable method in the comments_controller. I've tried a couple different variations of the method but the second one works best for my app and it was working when the url's had their id's in them. But since I overwrote the to_param to use my random permalink commenting stopped working because it's trying to find theid where it equals the permalink. Since it seems to try to find the id through the url, how do I pass the the actual id and not the permalink or how do I find commentable by it's permalink instead of id?
It's hard to tell if your param will always be the value of id or always be the permalink, or will sometimes be an id and sometimes a permalink.
If it will always be a permalink, then do:
#commentable = klass.find_by_permalink(params["#{klass.name.underscore}_id"])
instead of
#commentable = klass.find(params["#{klass.name.underscore}_id"])
If it is sometimes id and sometimes other, then you will need make logic to determine which is needed based on the class.
So that multiple people can be an administrator to a business page, we've created a model called administration where people can apply to be an admin of a business and thus the status of "0" is "pending" and "1" is accepted.
How can I prevent users from editing a page where their status for i is still "0" (pending).
class Administration < ActiveRecord::Base
attr_accessible :business_id, :user_id, :status
belongs_to :user
belongs_to :business
scope :pending, where('status = ?',0).order("updated_at desc")
def self.new_by_user_business( user, business)
admin = self.new
admin.business_id = business.id
admin.user_id = user.id
admin.status = 0
admin.save!
end
end
Here is the current "edit page"
<h1>Editing business</h1>
<%= render 'form1' %>
Here is the business controller.
class BusinessesController < ApplicationController
respond_to :html, :xml, :json
before_filter :authenticate_user!, except: [:index, :show]
def index
#businesses = Business.all
respond_with(#businesses)
end
def show
#business = Business.find(params[:id])
if request.path != business_path(#business)
redirect_to #business, status: :moved_permanently
end
end
def new
#business = Business.new
3.times { #business.assets.build }
respond_with(#business)
end
def edit
#business = get_business(params[:id])
#avatar = #business.assets.count
#avatar = 3-#avatar
#avatar.times {#business.assets.build}
end
def create
#business = Business.new(params[:business])
if #business.save
redirect_to #business, notice: 'Business was successfully created.'
else
3.times { #business.assets.build }
render 'new'
end
end
def update
#business = get_business(params[:id])
if #business.update_attributes(params[:business])
flash[:notice] = "Successfully updated Business."
end
#avatar = #business.assets.count
#avatar = 3-#avatar
#avatar.times {#business.assets.build}
respond_with(#business)
end
def destroy
#business = get_business(params[:id])
#business.destroy
respond_with(#business)
end
def my_business
#business = Business.all
end
def business_tickets
#user = current_user
#business = get_business(params[:id])
#tickets = #business.tickets
#business_inbox = TicketReply.where(:email => #business.callred_email)
end
def your_business
#user = current_user
#business = get_business(params[:id])
if #business.users.map(&:id).include? current_user.id
redirect_to my_business_businesses_path, notice: 'You are already an administator of this business.'
else
#admin = Administration.new_by_user_business( #user, #business)
BusinessMailer.delay(queue: "is_your_business", priority: 20, run_at: 5.minutes.from_now).is_your_business(#user,#business)
redirect_to #business, notice: 'Thank you for claiming your business, and we will be in touch with you shortly.'
end
end
def view_message
# #business = Business.find(params[:business_id])
#ticket = Ticket.find(params[:id])
#reply = #ticket.ticket_replies
end
private
def get_business(business_id)
#business = Business.find(business_id)
end
end
You could add a before_filter to check the status. You will have to change some of the logic but this is the idea
class BusinessesController < ApplicationController
before_filter :restrict_access, :only => [:edit, :update]
private
def restrict_access
#business = get_business(params[:id])
redirect to root_path, :notice => "Not Authorized" unless current_user.status == 1
end
end
I upgraded to rails 4 and now I am no longer able to register users on my app. It seems like my gallery (carrierewave) has broken down. I have inspected the code and can't notice anything that would stop it from working now. I get a undefined method `galleries' and it points to def setup_gallery: self.galleries << Gallery.create and under def create: if #user.save
Fresh eyes on my code would be great.
Users controller:
class UsersController < ApplicationController
respond_to :html, :json
def settings
#user = User.find(id_params)
end
def new
#user = User.new
end
def profile
#profile = User.profile
end
def create
#user = User.new(user_params)
if #user.save
UserMailer.registration_confirmation(#user).deliver
session[:user_id] = #user.id
redirect_to root_url, notice: "Thank you for signing up!"
else
render "new"
end
end
def show
#user = User.find(id_params)
end
def edit
#user = User.find(id_params)
end
def index
#users = User.all
end
def destroy
User.find(id_params).destroy
flash[:success] = "User deleted."
redirect_to users_url
end
def update
#user = if current_user.has_role?(:admin)
User.find(id_params)
else
current_user
end
#user.update_attributes(user_params)
respond_with #user
end
private
def user_params
params.require(:user).permit(:name, :email, :username, :password, :zip_code, :birthday, :role)
end
def id_params
params.require(:id).permit(:name)
end
end
User model:
# models/user.rb
after_create :setup_gallery
def received_messages
Message.received_by(self)
end
def unread_messages?
unread_message_count > 0 ? true : false
end
def unread_messages
received_messages.where('read_at IS NULL')
end
def sent_messages
Message.sent_by(self)
end
# Returns the number of unread messages for this user
def unread_message_count
eval 'messages.count(:conditions => ["recipient_id = ? AND read_at IS NULL", self.user_id])'
end
def to_s; username
end
def has_role?(role_name)
role.present? && role.to_sym == role_name.to_sym
end
def send_password_reset
generate_token(:password_reset_token)
self.password_reset_sent_at = Time.zone.now
save!
UserMailer.password_reset(self).deliver
end
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
private
def setup_gallery
self.galleries << Gallery.create
end
end
photos controller:
class PhotosController < ApplicationController
def new
#photo = Photo.new
end
def create
#photo = Photo.new(photo_params)
#photo.user = current_user
if #photo.save
flash[:notice] = "Successfully created photos."
redirect_to :back
else
render :action => 'new'
end
end
def edit
#photo = Photo.find(id_params)
end
def update
#photo = Photo.find(id_params)
if #photo.update_attributes(photo_params)
flash[:notice] = "Successfully updated photo."
redirect_to #photo.gallery
else
render :action => 'edit'
end
end
def destroy
#photo = Photo.find(id_params)
#photo.destroy
flash
[:notice] = "Successfully destroyed photo."
redirect_to #photo.gallery
end
private
def user_params
params.require(:user).permit(:name)
end
def id_params
params.require(:id).permit(:name)
end
end
After some trial and error I found that I had to change the private method in the user model.
What works is,
Gallery.create(user: self)
Thanks for those who responded to help!