1 error prohibited this channel from being saved: - ruby-on-rails

i have a rails app with users and posts, i have added another sacffold called channels, now the relationship goes like the user can create both post and channels and the channels belongs to users, post belongs to both users and channels, to add user id to channels i have created a migration, everything looks good but i am getting this error while creating a channel.
(Here is a screenshot of the exact error)
This is what am getting on the command line:
Started POST "/channels" for 127.0.0.1 at 2017-12-16 13:30:32 +0530
Processing by ChannelsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"IJvvEe+TR6buacH5UwtiLSJglMkq7a+Q4x7VOTqALcGka4j6tG7lPi/7kYnCQ/nzmO7PNe2eSan3sBz9NqKV2g==", "channel"=>{"name"=>"dhfkdhfk", "description"=>"jdfjdfh", "tagline"=>"jdfjdfhj", "category"=>"jdfjdf", "avatar"=>""}, "commit"=>"Create Channel"}
User Load (2.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
(2.6ms) BEGIN
(1.8ms) ROLLBACK
Rendered channels/_form.html.erb (11.5ms)
Rendered channels/new.html.erb within layouts/application (13.3ms)
Rendered layouts/_avatar_dropdown.html.erb (7.4ms)
Rendered layouts/_header.html.erb (12.6ms)
Rendered layouts/_alert_messages.html.erb (0.5ms)
Completed 200 OK in 367ms (Views: 345.3ms | ActiveRecord: 6.7ms)
Add_user_id_to_channel.rb
class AddUserIdToChannels < ActiveRecord::Migration
def change
add_reference :channels, :user, index: true, foreign_key: true
end
end
channel.rb
class Channel < ActiveRecord::Base
validates :name, :description, :user_id, presence: true
belongs_to :user
has_many :posts, dependent: :destroy
end
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, :omniauth_providers => [:facebook, :twitter, :google_oauth2]
act_as_mentionee
validates :username, presence: true
validate :avatar_image_size
has_many :posts, dependent: :destroy
has_many :channels, dependent: :destroy
has_many :responses, dependent: :destroy
has_many :likes, dependent: :destroy
after_destroy :clear_notifications
after_commit :send_welcome_email, on: [:create]
mount_uploader :avatar, AvatarUploader
include UserFollowing
include TagFollowing
include SearchableUser
include OmniauthableUser
private
# Validates the size on an uploaded image.
def avatar_image_size
if avatar.size > 5.megabytes
errors.add(:avatar, "should be less than 5MB")
end
end
# Returns a string of the objects class name downcased.
def downcased_class_name(obj)
obj.class.to_s.downcase
end
# Clears notifications where deleted user is the actor.
def clear_notifications
Notification.where(actor_id: self.id).destroy_all
end
def send_welcome_email
WelcomeEmailJob.perform_later(self.id)
end
end
user_controller
class UsersController < ApplicationController
before_action :authenticate_user!, only: [:edit, :update]
before_action :authorize_user, only: [:edit, :update]
before_action :set_user, only: [:show, :edit, :update]
def show
#followers_count = #user.followers.count
#following_count = #user.following.count
#latest_posts = #user.posts.latest(3).published
#recommended_posts = #user.liked_posts.latest(4).published.includes(:user)
end
def update
if #user.update(user_params)
redirect_to #user
else
render :edit, alert: "Could not update, Please try again"
end
end
private
def set_user
#user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:description, :avatar, :location, :username)
end
def authorize_user
unless current_user.slug == params[:id]
redirect_to root_url
end
end
end
channel_controller
class ChannelsController < ApplicationController
before_action :set_channel, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:show]
before_action :authorize_user, only: [:edit, :update, :destroy]
# GET /channels
# GET /channels.json
def index
#channels = Channel.all
end
# GET /channels/1
# GET /channels/1.json
def show
end
# GET /channels/new
def new
#channel = Channel.new
#channel = current_user.channels.build
#user = current_user
end
# GET /channels/1/edit
def edit
end
# POST /channels
# POST /channels.json
def create
#channel = current_user.channels.build(channel_params)
#channel = Channel.new(channel_params)
#user = current_user
respond_to do |format|
if #channel.save
format.html { redirect_to #channel, notice: 'Channel was successfully created.' }
format.json { render :show, status: :created, location: #channel }
else
format.html { render :new }
format.json { render json: #channel.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /channels/1
# PATCH/PUT /channels/1.json
def update
respond_to do |format|
if #channel.update(channel_params)
format.html { redirect_to #channel, notice: 'Channel was successfully updated.' }
format.json { render :show, status: :ok, location: #channel }
else
format.html { render :edit }
format.json { render json: #channel.errors, status: :unprocessable_entity }
end
end
end
# DELETE /channels/1
# DELETE /channels/1.json
def destroy
#channel.destroy
respond_to do |format|
format.html { redirect_to channels_url, notice: 'Channel was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_channel
#channel = Channel.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def channel_params
params.require(:channel).permit(:name, :description, :tagline, :category, :avatar, :user_id)
end
def authorize_user
begin
#channel = current_user.channels.find(params[:id])
rescue
redirect_to root_url
end
end
end

In model of channel you made it 'user_id' compulsory filed by adding presence: true
validates :name, :description, :user_id, presence: true
so you have to pass user_id in your parameters. you can do that by adding hidden_filed in your view as
<%= f.hidden_field :user_id, value: #user %>
or if you don't required 'user_id' remove form validates like these:
validates :name, :description, presence: true

Change
#channel = current_user.channels.build(channel_params)
#channel = Channel.new(channel_params)
To
#channel = current_user.channels.build(channel_params)

Related

error while adding tags to a post in rails

I wanted to add tags to my products in rails project, so i watched a youtube video how to do it (https://www.youtube.com/watch?v=rzx5MrCa0Pc&t=254s)
I did all he did, but i when i add a new product i get an error -
'New Product
1 error prohibited this product from being saved:
User must exist' , right above my new product form
how do i fix it.
MY ROUTES
Rails.application.routes.draw do
devise_for :users, :controllers => { :registrations => "registrations"}
resources :products
get 'home/ContactUs'
get 'home/Login'
get 'home/Store'
get 'home/blogs'
get 'home/index'
resources :home
root 'home#index'
MY PRODUCT MODEL
class Product < ActiveRecord::Base
belongs_to :user
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings
def self.tagged_with(name)
Tag.find_by!(name: name).products
end
def all_tags=(names)
# names="music, spotify"
self.tags = names.split(',').map do |name|
Tag.where(name: name).first_or_create!
end
end
def all_tags
tags.map(&:name).join(", ")
end
end
TAG MODEL
class Tag < ApplicationRecord
has_many :taggings, dependent: :destroy
has_many :products, through: :taggings
end
TAGGINGS MODEL
class Tagging < ActiveRecord::Base
belongs_to :product
belongs_to :tag
end
USER MODEL
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :products
end
PRODUCT_CONTROLLER
class ProductsController < ApplicationController
# before_action :authenticate_user!
before_action :set_product, only: [:show, :edit, :update, :destroy]
# GET /products
# GET /products.json
def index
if params[:tag]
#products = Product.tagged_with(params[:tag])
else
#products = Product.all
end
end
# GET /products/1
# GET /products/1.json
def show
end
# GET /products/new
def new
#product = Product.new
end
# GET /products/1/edit
def edit
end
# POST /products
# POST /products.json
def create
#product = Product.new(product_params)
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: #product }
else
format.html { render :new }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /products/1
# PATCH/PUT /products/1.json
def update
respond_to do |format|
if #product.update(product_params)
format.html { redirect_to #product, notice: 'Product was successfully updated.' }
format.json { render :show, status: :ok, location: #product }
else
format.html { render :edit }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# DELETE /products/1
# DELETE /products/1.json
def destroy
#product.destroy
respond_to do |format|
format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_product
#product = Product.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def product_params
params.require(:product).permit(:filetype, :title, :img_url, :description, :all_tags, :price, :uploaded_by, :tutorial_url)
end
end
User must exist
The problem is Product belongs to User but you are trying to create the product without passing user_id which will create an orphan product
Solution: Change
def create
#product = Product.new(product_params)
to
def create
#product = current_user.products.new(product_params)
Also, You will need to change set_product method to make sure you can update or delete only products created by user
def set_product
#product = current_user.products.find(params[:id])
end

User has_many reviews association

I'm trying to create a way for users to review other users.
When I try going on www.site.com/users/1/reviews/new , i get redirected to my homepage with 'resource not found'. I'm guessing it has to do with my routes?
routes.rb
Rails.application.routes.draw do
devise_for :users,
:controllers => { registrations: 'registrations',
omniauth_callbacks: 'omniauth_callbacks'} #<-- that thing is for STRIPE!
#STRIPE
resources :charges
#MAILBOXER
resources :conversations, only: [:index, :show, :destroy] do
member do
post :reply
post :restore
post :mark_as_read
end
collection do
delete :empty_trash
end
end
resources :messages, only: [:new, :create]
#user reviews (THE PROBLEM)
resources :users do
resources :reviews
end
#categories associatoin
resources :categories, except: [:destroy]
root 'home#index'
get 'profile', to: 'users#show'
end
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable
#Categories association stuff
has_many :user_categories
has_many :categories, through: :user_categories
#user review association stuff
has_many :reviews
acts_as_messageable
def mailboxer_email(object)
email
end
end
review.rb
class Review < ActiveRecord::Base
belongs_to :user
end
reviews_controller.rb
class ReviewsController < ApplicationController
before_action :set_review, only: [:show, :edit, :update, :destroy]
before_action :set_user
before_action :authenticate_user!
# GET /reviews
# GET /reviews.json
def index
#reviews = Review.all
end
# GET /reviews/1
# GET /reviews/1.json
def show
end
# GET /reviews/new
def new
#review = Review.new
end
# GET /reviews/1/edit
def edit
end
# POST /reviews
# POST /reviews.json
def create
#review = Review.new(review_params)
#review.user_id = current_user.id
#review.user_id = #user.id
end
# PATCH/PUT /reviews/1
# PATCH/PUT /reviews/1.json
def update
respond_to do |format|
if #review.update(review_params)
format.html { redirect_to #review, notice: 'Review was successfully updated.' }
format.json { render :show, status: :ok, location: #review }
else
format.html { render :edit }
format.json { render json: #review.errors, status: :unprocessable_entity }
end
end
end
# DELETE /reviews/1
# DELETE /reviews/1.json
def destroy
#review.destroy
respond_to do |format|
format.html { redirect_to reviews_url, notice: 'Review was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_review
#review = Review.find(params[:id])
end
def set_user
#user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def review_params
params.require(:review).permit(:rating, :comment)
end
end
def set_user
#user = User.find(params[:id])
end
should be:
def set_user
#user = User.find(params[:user_id])
end

Trouble deploying pundit authorization in Rails 4.2.4 with devise

I am a junior developer working on my first web application for a customer, an electronic commerce portal using Rails 4.2.4, Devise and a pins scaffolding.
Devise is working great and anyone can signup and login and CRUD a pin.
Problem: Users cannot be given access to CUD as the pins contain live customer products that are for sale.
I am therfore trying to implement pundit so that users are purely RESTRICTED to read only and CANNOT create, update or destroy pins, Only the business owner can do so in an Admin capacity.
Currently, I am getting the error "Pundit::NotDefinedError in PinsController#new
1.) How can I add myself as the admin(is this through a migration?)
2) How can I get Pundit working.
class PinsController < ApplicationController
before_action :set_pin, only: [:show, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
if params[:search].present? && !params[:search].nil?
#pins = Pin.where("description LIKE ?", "%#{params[:search]}%").paginate(:page => params[:page], :per_page => 15)
else
#pins = Pin.all.order("created_at DESC").paginate(:page => params[:page], :per_page => 15)
end
end
def show
end
def new
#pin = current_user.pins.build
authorize #pins
end
def edit
end
def create
#pin = current_user.pins.build(pin_params)
if #pin.save
redirect_to #pin, notice: 'Pin was successfully created.'
else
render :new
end
end
def update
if #pin.update(pin_params)
redirect_to #pin, notice: 'Pin was successfully updated.'
else
render :edit
end
end
def destroy
#pin.destroy
redirect_to pins_url
end
private
# Use callbacks to share common setup or constraints between actions.
def set_pin
#pin = Pin.find_by(id: params[:id])
end
def correct_user
#pin = current_user.pins.find_by(id: params[:id])
redirect_to pins_path, notice: "Not authorized to edit this pin" if #pin.nil?
end
# Never trust parameters from the scary internet, only allow the white list through.
def pin_params
params.require(:pin).permit(:description, :image)
end
end
Blockquote
class ApplicationPolicy
attr_reader :user, :pin
def initialize(user, pin)
raise Pundit::NotAuthorizedError, "must be logged in" unless user
#user = user
#pin = pin
end
def index?
true
end
def show?
scope.where(:id => record.id).exists?
end
def create?
user.admin?
end
def new?
user.admin?
end
def update?
user.admin?
end
def edit?
update?
end
def destroy?
user.admin?
end
def scope
Pundit.policy_scope!(user, record.class)
end
class Scope
attr_reader :user, :scope
def initialize(user, scope)
#user = user
#scope = scope
end
def resolve
scope
end
end
end
Blockquote
class ApplicationController < ActionController::Base
include Pundit
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
protect_from_forgery with: :exception
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :name
devise_parameter_sanitizer.for(:account_update) << :name
end
private
def user_not_authorized
flash[:warning] = "You are not authorized to perform this action."
redirect_to(request.referrer || root_path)
end
end
Blockquote
class Pin < ActiveRecord::Base
belongs_to :user
has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png"]
validates :image, presence: true
validates :description, presence: true
end
Blockquote
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :pins, dependent: :destroy
validates :name, presence: true
end

Can I edit all users as admin in devise with cancan

I have set up users with devise and each user can select a role. What I am trying to do is allow admins to be able to edit any user on the site if they have role admin. I currently have a UsersController setup like this:
class UsersController < ApplicationController
before_filter :authenticate_user!, only: [:index, :new, :edit, :update, :destroy]
skip_before_filter
def index
#users = User.order('created_at DESC').all
end
def show
#user = User.friendly.find(params[:id])
#users_authors = User.all_authors
end
# get authors index in here
def authors
end
def create
#user = User.create(user_params)
end
def edit
#user = User.find(params[:id])
end
def update
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
def destroy
#user = User.find(params[:id])
#user.destroy
if #user.destroy
redirect_to users_url, notice: "User deleted."
end
end
private
def user_params
params.require(:user).permit(:avatar, :email, :name, :biography, :role_id, :book_id, :username, :password, :password_confirmation)
end
end
This is trying to create a CRUD to edit users which works but I need to be able to populate the forms in the users/edit view wityh the correct selected users details. I my devise controller I have this setup:
class Admin::UsersController < Admin::BaseController
helper_method :sort_column, :sort_direction
before_filter :find_user, :only => [:edit, :update, :show, :destroy]
def index
#q = User.search(params[:q])
#users = find_users
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
redirect_to admin_users_path, :notice => "Successfully created user."
else
render :new
end
end
def show
end
def edit
#user = User.find(params[:id])
end
def update
if #user.update_attributes(user_params)
redirect_to admin_users_path, :notice => "Successfully updated user."
else
render :edit
end
end
def destroy
#user.destroy
redirect_to admin_users_path, :notice => "User deleted."
end
protected
def find_user
#user = User.find(params[:id])
end
def find_users
search_relation = #q.result
#users = search_relation.order(sort_column + " " + sort_direction).references(:user).page params[:page]
end
def sort_column
User.column_names.include?(params[:sort]) ? params[:sort] : "created_at"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "desc"
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:email,:username,:name,:biography,:role_id,:book_id,:role_name,:password,:password_confirmation,:encrypted_password,:reset_password_token,:reset_password_sent_at,:remember_created_at,:sign_in_count,:current_sign_in_at,:last_sign_in_at,:current_sign_in_ip,:last_sign_in_ip)
end
end
For clarity here is the user model:
class User < ActiveRecord::Base
belongs_to :role
has_many :books, dependent: :destroy
has_many :ideas, dependent: :destroy
accepts_nested_attributes_for :books
accepts_nested_attributes_for :ideas
def confirmation_required?
false
end
extend FriendlyId
friendly_id :username, use: [:slugged, :finders]
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
has_attached_file :avatar, styles: {
large: "600x450#",
medium: "250x250#",
small: "100x100#"
}, :default_url => "/images/:style/filler.png"
#validates_attachment_content_type :avatar, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
validates :avatar, :email, :username, :password, presence: true
def self.all_authors
User.select('users.id, users.username, users.role_id AS USER_ROLE')
.joins(:role).where(users: {role_id: '2'})
end
before_create :set_default_role
private
def set_default_role
self.role ||= Role.find_by_name('Admin')
end
end
In my routes I added a new route for users below the devise users resource as suggested on devise wiki like so:
devise_for :users, :path_prefix => 'my', :path_names => { :sign_up => "register" }
namespace :admin do
resources :users
end
Can anyone help with adding the ability of admins being able to edit all users here, I think its right but I cannot get the correct data into the forms in edit, it uses the current logged users details only.
A first draft for your ability.rb would be:
class Ability
include CanCan::Ability
def initialize(user)
# ...
if user.admin?
can :manage, User
end
# ...
end
end
And then in your user's controller remove the before_filter :find_user, :only => [:edit, :update, :show, :destroy] and related method, and use
load_and_authorize_resource :user
That would load the user from the URL and authorize! it using CanCan. You'll also need to handle the CanCan::AccessDenied exception for non-admin users visiting those pages, but that is another question that you can check in the CanCan docs.
When you visit admin_users_path routes you'll be able to CRUD them if you have the views ready and working.

What am I missing to get a profile page to include additional fields such as address, avatar, phone number

I am using Ruby on Rails and utilized devise for my log in and registration. After signing up, I get this error message:
NoMethodError in Devise::SessionsController#create undefined method profile_path' for #<Devise::SessionsController:0x007f9425b1f9c0>
I used rails generate scaffold profile and have the following code:
profiles_controller.rb
class ProfilesController < ApplicationController
before_action :set_profile, only: [:show, :edit, :update, :destroy]
def profile
end
# GET /profiles
# GET /profiles.json
def index
#profiles = Profile.all
end
# GET /profiles/1
# GET /profiles/1.json
def show
end
# GET /profiles/new
def new
#profile = Profile.new
end
# GET /profiles/1/edit
def edit
#profile = Profile.find_by user_id: current_user.id
#attributes = Profile.attribute_names - %w(id user_id created_at updated_at)
end
# POST /profiles
# POST /profiles.json
def create
#profile = Profile.new(profile_params)
respond_to do |format|
if #profile.save
format.html { redirect_to #profile, notice: 'Profile was successfully created.' }
format.json { render :show, status: :created, location: #profile }
else
format.html { render :new }
format.json { render json: #profile.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /profiles/1
# PATCH/PUT /profiles/1.json
def update
respond_to do |format|
if #profile.update(profile_params)
format.html { redirect_to #profile, notice: 'Profile was successfully updated.' }
format.json { render :show, status: :ok, location: #profile }
else
format.html { render :edit }
format.json { render json: #profile.errors, status: :unprocessable_entity }
end
end
end
# DELETE /profiles/1
# DELETE /profiles/1.json
def destroy
#profile.destroy
respond_to do |format|
format.html { redirect_to profiles_url, notice: 'Profile was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_profile
#profile = Profile.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def profile_params
params[:profile]
end
end
application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :name
devise_parameter_sanitizer.for(:account_update) << :name
end
def after_sign_in_path_for(resource)
profile_path(resource)
end
def after_sign_up_path_for(resource)
profile_path(resource)
end
end
profile.rb
class Profile < ActiveRecord::Base
belongs_to :user
end
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :pins, dependent: :destroy
validates :name, presence: true
has_one :profile
before_create :build_profile #creates profile at user registration
end
routes.rb
Rails.application.routes.draw do
resources :profiles, only: [:edit]
resources :pins
devise_for :users
#devise_for :installs
root "pins#index"
get "about" => "pages#about"
Thanks.
You need to use the plural: profiles_path rather than profile_path, in application_controller.rb.

Resources