uninitialized constant User::CompaniesRate - ruby-on-rails

I am newbie in rails. I am trying to generate a page form. but I am geting this error.
I could not understand where is my problem.
this was the error showing and it was highlighting in this line
#companies_rates =#user.companies_rates
Here I will be having userpage, companies_rate and page3 where each pages have user id and companies rate has an column same column also exit in the page 3. Now i want display companies_rate and page 3 seperately
NameError in UsersController#show
uninitialized constant User::CompaniesRate
#user = User.find(params[:id])
#companies_mines= #user.companies_mines
**#companies_rates =#user.companies_rates**
#title=#user.name
end
Here is my users controller
class UsersController < ApplicationController
before_action :signed_in_user,
only: [:index, :edit, :update, :destroy, :following, :followers]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
def index
#users = User.paginate(page: params[:page])
end
def show
#user = User.find(params[:id])
#companies_mines= #user.companies_mines
#companies_rates =#user.companies_rates
#title=#user.name
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
sign_in #user
flash[:success] = "Welcome to skillable"
redirect_to #user
else
render 'new'
end
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to #user
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User destroyed."
redirect_to users_url
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
# Before filters
def correct_user
#user = User.find(params[:id])
redirect_to(root_url) unless current_user?(#user)
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
And here is my companies_rate controller
class CompaniesRatesController < ApplicationController
before_action :signed_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def index
#companies_rates = companies_rates.all
end
def show
#companies_rates = companies_rate.find(params[:id])
end
def new
#companies_rates = companies_rates.new
end
def create
#companies_rates = companies_rates .new(params[:company,:r1,:r2,:r3])
if #post.save
redirect_to companies_rates _path, :notice => "Your post was saved"
else
render "new"
end
end
def edit
end
def update
end
def destroy
end
private
def companies_rates_params
params.require(:companies_rates).permit(:company, :r1, :r2, :r3 )
end
def correct_user
#companies_rates = current_user.companies_rates.find_by(id: params[:id])
redirect_to root_url if #ompanies_rates.nil?
end
end
Here is my users modal
class User < ActiveRecord::Base
attr_accessor :password
#attr_accessible :name, :email, :password, :password_confirmation
has_many :companies_mines
has_many :companies_rates
before_save { self.email = email.downcase }
before_create :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.encrypt(token)
Digest::SHA1.hexdigest(token.to_s)
end
private
def create_remember_token
self.remember_token = User.encrypt(User.new_remember_token)
end
end
Here is my companies_rates
class CompaniesRates < ActiveRecord::Base
#attr_accessible :company, :r1, :r2, :r3
belongs_to :user
validates :company, presence: true, length: { maximum: 140 }
validates :user_id, presence: true
belongs_to :user
default_scope :order => 'companies_rates.created_at DESC'
end
Can any on tell what is my problem and how to solve it.

Change the model name to CompaniesRate.Model name should be singular

Related

NoMethodError- Cant figure out

I am working on a pinterest clone and I am having some trouble when i try to create a new pin. I get "NoMethodError - undefined method pins' for nil:NilClass: app/controllers/api/pins_controller.rb:19:in create'"
I am not sure what else to try. I dont know why it doesnt have access to pins. Any suggestions???
routes.rb
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root to: 'static_pages#root'
namespace :api, defaults: { format: :json } do
resources :users, only: [:show,:new, :create, :index]
resource :session, only: [:new, :create, :destroy, :show]
resources :pins, only: [:create, :show, :index, :edit, :destroy]
resources :boards, only: [:create, :show, :edit, :destroy]
end
end
user.rb
class User < ApplicationRecord
attr_reader :password
validates :username, presence: true, uniqueness: true
validates :password_digest, :session_token, presence: true
validates :password, length: { minimum: 6 }, allow_nil: true
after_initialize :ensure_session_token
has_many :pins,
foreign_key: :author_id,
class_name: :Pin
has_many :boards,
foreign_key: :author_id,
class_name: :Board
has_many :pins_in_boards,
through: :boards,
source: :boards_pins
def self.find_by_credentials(username, password)
user = User.find_by(username: username)
return nil unless user
user.is_password?(password) ? user : nil
end
def password=(password)
#password = password
self.password_digest = BCrypt::Password.create(password)
end
def is_password?(password)
BCrypt::Password.new(self.password_digest).is_password?(password)
end
def ensure_session_token
self.session_token ||= SecureRandom.urlsafe_base64
end
def reset_session_token!
self.session_token = SecureRandom.urlsafe_base64
self.save
self.session_token
end
end
users_controller.rb
class Api::UsersController < ApplicationController
def show
#user = User.find_by(username: params[:id])
if #user
render :show
else
render json: #user.errors.full_messages, status: 404
end
end
def new
#user = User.new
render :new
end
def index
#users =User.all
render :index
end
def create
#user = User.new(user_params)
if #user.save
sign_in(#user)
render "api/users/show"
else
render json: #user.errors.full_messages, status: 422
end
end
private
def user_params
params.require(:user).permit(:password, :username)
end
end
pins_controller.rb
class Api::PinsController < ApplicationController
def index
#pins = user.pins
end
def new
#pin = Pin.new(user_id: current_user.id)
render :new
end
def show
#pin = Pin.find(params[:id])
render :show
end
def create
#pin = current_user.pins.new(pin_params)
if #pin.save
render :show
else
render json: #pin.errors.full_messages, status: 422
end
end
def edit
#pin = Pin.find(params[:id])
unless #pin.author_id == current_user.id
render "api/pins/show"
else
render :edit
end
end
def destroy
pin = current_user.pins.find(params[:id])
pin.destroy
end
private
def pin_params
params.require(:pin).permit(
:title,
:description,
:url,
:author_id,
:photo
)
end
def user
#user ||= User.find(params[:user_id])
end
def pin
#pin ||= current_user.pins.find(params[:id])
end
end
pin.rb
class Pin < ApplicationRecord
validates :title, :description, :author_id, presence: true
belongs_to :user
belongs_to :board
has_many :boards
has_one_attached :photo
has_many :users,
through: :boards,
source: :author
end
creat_pin_form_container.jsx
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import PinForm from './pin_form';
import { createPin } from '../../actions/pins_actions';
import { openModalForm, closeModalForm } from '../../actions/modal_form_actions';
const mapStateToProps = state => ({
pin: {
title: '',
description: '',
photoFile: null
},
formType: 'New Pin'
});
const mapDispatchToProps = dispatch => ({
action: pin => dispatch(createPin(pin)),
closeModalForm: () => dispatch(closeModalForm())
});
export default connect(mapStateToProps, mapDispatchToProps)(PinForm);
pin_form.jsx
import React from 'react';
class PinForm extends React.Component {
constructor(props) {
super(props);
this.state = this.props.pin;
this.handleSubmit = this.handleSubmit.bind(this);
this.handleFile = this.handleFile.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const formData = new FormData();
formData.append('pin[title]', this.state.title);
formData.append('pin[description]', this.state.description);
formData.append('pin[url]', this.state.url);
formData.append('pin[photo]', this.state.photoFile);
this.props.action(formData, this.state.id);
}
update(field) {
return e => this.setState({ [field]: e.currentTarget.value });
}
handleFile(e){
this.setState({ photoFile: e.currentTarget.files[0] })
}
render() {
return (
<div className="pin-form-container">
<form onSubmit={this.handleSubmit}>
This is occurring because the value of current_user is currently set to nil. You need to make sure you have a logged in user.

Ruby on Rails || Adding conferences to users

I'm creating an app where u can see all conferences in the world.
What I've got:
creating an conference
showing all conferences
Now what I want to create is an button that let's me add a conference to a user.
What do I want to accomplish with this:
adding conference to users
showing added conferences in a list
viewing conferences and adding content
I was thinking of an button that copies the attributes of selected object and adds it to an selected user for future manipulation and viewing of the conference
I'm asking if someone can tell me how to accomplish this
https://consulegem-salman15.c9users.io/conferences
Migration conferences
class CreateConferences < ActiveRecord::Migration[5.0]
def change
create_table :conferences do |t|
t.string :conference
t.string :country
t.string :month
t.string :presence
t.string :audience
t.integer :cost
t.text :content
t.references :user, foreign_key: true
t.timestamps
end
add_index :conferences, [:user_id, :created_at]
end
end
Controller conference
class ConferencesController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
before_action :admin_user, only: :destroy
def index
#conferences = Conference.paginate(page: params[:page])
if params[:search]
#conferences = Conference.search(params[:search]).order("created_at DESC").paginate(page: params[:page])
else
#conferences = Conference.all.order('created_at DESC').paginate(page: params[:page])
end
end
def new
#user = User.new
#conference = Conference.new
end
def create
#conference = current_user.conferences.build(conference_params)
if #conference.save
flash[:success] = "conference created!"
redirect_to conferences_path
else
#feed_items = current_user.feed.paginate(page: params[:page])
render 'new'
end
end
def destroy
#conference.destroy
flash[:success] = "conference deleted"
redirect_to request.referrer || root_url
end
private
def conference_params
params.require(:conference).permit(:conference,:country , :month, :presence, :audience, :cost ,:picture)
end
# Confirms an admin user.
def admin_user
redirect_to(root_url) unless current_user.admin?
end
def correct_user
#conference = current_user.conferences.find_by(id: params[:id])
redirect_to root_url if #conference.nil?
end
end
Model controller
class Conference < ApplicationRecord
belongs_to:user
default_scope -> { order(created_at: :desc) }
mount_uploader :picture, PictureUploader
validates :user_id, presence: true
validates :conference, presence: true, length: { maximum: 140 }
validate :picture_size
scope :conference, -> (conference) { where conference: conference }
def self.search(search)
where("conference LIKE ? OR country LIKE ? OR month LIKE ?", "%#{search}%", "%#{search}%", "%#{search}%")
end
private
# Validates the size of an uploaded picture.
def picture_size
if picture.size > 5.megabytes
errors.add(:picture, "should be less than 5MB")
end
end
end
The answer I found was by adding a SubscriptionsController that is nested in the ConferenceController and a RelationshipController
SubscriptionController
class SubscriptionsController < ApplicationController
before_action :set_conference, only: :create
def index
#subscriptions = current_user.subscriptions
#subscriptions = Subscription.paginate(page: params[:page])
end
def show
#subscription = Subscription.find_by(id: params[:id])
end
def create
if current_user.subscriptions.create(conference: #conference)
flash[:success] = "You are now subscribed to { #conference.conference }"
else
flash[:error] = "Could not create subscription."
end
redirect_to conferences_path
end
def destroy
#subscription = current_user.subscriptions.find(params[:id])
if #subscription.destroy
flash[:success] = "You are no longer subscribed to { #conference.conference }"
else
flash[:error] = "Oh noes"
end
redirect_to conferences_path
end
def set_conference
#conference = Conference.find_by id: params["conference_id"]
end
end
RelationshipController
class RelationshipsController < ApplicationController
before_action :logged_in_user
def create
#conference = Conference.find(params[:followed_id])
current_user.follow(#conference)
respond_to do |format|
format.html { redirect_to #conference }
format.js
end
end
def destroy
#user = Relationship.find(params[:id]).followed
current_user.unfollow(#user)
respond_to do |format|
format.html { redirect_to #user }
format.js
end
end
end
ConferenceController
class ConferencesController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
before_action :admin_user, only: :destroy
def index
#conferences = Conference.paginate(page: params[:page])
if params[:search]
#conferences = Conference.search(params[:search]).order("created_at DESC").paginate(page: params[:page])
else
#conferences = Conference.all.order('created_at DESC').paginate(page: params[:page])
end
end
def show
#conference = Conference.find(params[:id])
end
def new
#user = User.new
#conference = Conference.new
end
def create
#conference = Conference.new(conference_params)
#conference.user = current_user
if #conference.save
flash[:success] = "conference created!"
redirect_to conferences_path
else
#feed_items = current_user.feed.paginate(page: params[:page])
render 'new'
end
end
def destroy
#conference.destroy
flash[:success] = "conference deleted"
redirect_to request.referrer || root_url
end
private
def conference_params
params.require(:conference).permit(:conference,:country , :month, :presence, :audience, :cost ,:picture)
end
# Confirms an admin user.
def admin_user
redirect_to(root_url) unless current_user.admin?
end
def correct_user
#conference = current_user.conferences.find_by(id: params[:id])
redirect_to root_url if #conference.nil?
end
end

Not able to find admin? while doing Michael Hartl's Tutorial

This is my users controller and i am doing michael hartl's tutorial but i am having problem in current_user.admin? in the admin_user method defined in users controller and also having problem in my destroy method as i am not able to delete user as well.
pls any solution??
class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
def index
#users = User.paginate(page: params[:page])
end
def new
#user = User.new
end
def show
#user = User.find(params[:id])
end
def create
#user = User.new(user_params)
if #user.save
flash[:success] = 'Welcome to the Sample App!'
redirect_to #user
else
render 'new'
end
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
flash[:success] = 'Profile Updated'
redirect_to #user
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = 'User deleted'
redirect_to users_url
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
def logged_in_user
unless logged_in?
store_location
flash[:danger] = 'Please log in.'
redirect_to login_url
end
end
def correct_user
#user = User.find(params[:id])
redirect_to(root_url) unless current_user?(#user)
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
User.rb
class User < ActiveRecord::Base
attr_accessor :remember_token
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: true
has_secure_password
validates :password, length: { minimum: 6 }
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
def User.new_token
SecureRandom.urlsafe_base64
end
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
def authenticated?(remember_token)
return false if remember_digest.nil?
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
def forget
update_attribute(:remember_digest, nil)
end
end
Link for the Delete
<li>
<%= gravatar_for user %>
<%= link_to user.name, user %>
<% if current_user.admin? && !current_user?(user) %>
| <%= link_to 'delete', user, method: :delete,
data: { confirm: 'You sure?' } %>
<% end %>
</li>

Session usage in rails 3.1.3, returning errors

I am in a process of upgrading my app from rails 2.3.11 to 3.2.x. Everything worked well untill 3.1.x where I faced issues in session handling. Earlier I have utilized cookies for session handling but now there is a question if I can use ActiveModel for handling sessions too?????
Secondly, while still playing around with cookies, I see this unavoidable undefined method error. Any suggestions to get around this error????
Here is my codes-
Session Controller:
class SessionsController < ApplicationController
def new
#title = "Sign in"
end
def create
#title = "create session"
user = User.authenticate(params[:session][:name], params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid username/password combination."
#title = "Sign in"
render 'new'
else
sign_in user
#partner = Partner.find(:first, :conditions => [ "user_id = ?", user.id])
logger.info "---------User loggin: " + current_user.name
redirect_back_or samplings_url
end
end
def destroy
#title = "Sign out"
logger.info "---------User log OUT: " + current_user.name
sign_out
redirect_to root_path
end
end
User Model:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password
EmailRegex = /\A[\w+\-._]+#[a-z\d\-.]+\.[a-z]+\z/i
validates_presence_of :name, :email
validates_length_of :name, :maximum => 50
validates_format_of :email, :with => EmailRegex
validates_uniqueness_of :email, :case_sensitive => false
has_many :microposts
validates_confirmation_of :password
validates_presence_of :password
validates_length_of :password, :within => 1..40
before_save :encrypt_password
def self.authenticate(name, submitted_password)
username = self.where(name: name)
return nil if username.nil?
return username if username.encrypted_password == encrypt(submitted_password)
end
def remember_me!
self.remember_token = encrypt("#{salt}--#{id}--#{Time.now.utc}")
save(validate=false)
end
private
def encrypt_password
unless password.nil? #due to def remember_me! method during sign in function call
self.salt = make_salt
self.encrypted_password = encrypt(password)
end
end
def encrypt(string)
secure_hash("#{salt}#{string}")
end
def make_salt
secure_hash("#{Time.now.utc}#{password}")
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
end
UserController:
class UsersController < AuthController
before_filter :authenticate, :only => [:index, :edit, :update]
before_filter :correct_user, :only => [:new, :create, :destroy]
before_filter :modify_user, :only => [:edit, :update]
filter_parameter_logging :password
def index
#users = User.all
#title = "users"
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #users }
end
end
def show
#user = User.find(params[:id])
#title = #user.name
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #user }
end
end
def new
redirect_to signin_path
if !current_user?(#user)
flash[:notice] = "Only the partner who create the risorse can modify it."
end
end
def create
#title = "sign up user"
#user = User.new(params[:user]) #hash of user attributes
if #user.save
sign_in #user
flash[:success] = "Welcome to the microaqua web application!"
redirect_to #user #equal as user_path(#user)
else
#title = "Sign up"
render 'new'
end
end
# GET /users/1/edit
def edit
#title = #user.name #"user"
end
def update
#title = #user.name #"user"
if #user.update_attributes(params[:user])
flash[:success] = "Profile updated."
redirect_to #user
else
#title = "Edit user"
render 'edit'
end
end
def destroy
redirect_to users_path
end
private
def correct_user
#user = User.find(params[:id])
reroute() unless signed_in_and_master?
end
def modify_user
#user = User.find(params[:id])
reroute() unless (current_user?(#user) or signed_in_and_master?)
end
def reroute()
flash[:notice] = "Only the partner can modify his own profile."
redirect_to(user_path(#user))
end
end
Error:
NoMethodError in SessionsController#create
undefined method `encrypted_password' for #<ActiveRecord::Relation:0x00000003632038>
.where always returns an array. Here is the code that is throwing the error in your user model:
def self.authenticate(name, submitted_password)
username = self.where(name: name)
return nil if username.nil?
return username if username.encrypted_password == encrypt(submitted_password)
end
You are calling .encrypted_password on an array. Change the code to this:
def self.authenticate(name, submitted_password)
username = self.where(name: name).first
return nil if username.nil?
return username if username.encrypted_password == encrypt(submitted_password)
end
If it is possible to get more than one user with the same name then you should iterate through the array and check every result.
As far as storing the session in the database, check out this SO question:Rails 3: Storing Session in Active Record (not cookie)

undefined method `downcase' for nil:NilClass railstutorial

I try railstutorial rails4.0
now 9.2.0 and no Rspec error.
but rails s has NoMethodError in Users#index when open /users
why?
app / models / user.rb
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
before_create :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.encrypt(token)
Digest::SHA1.hexdigest(token.to_s)
end
private
def create_remember_token
self.remember_token = User.encrypt(User.new_remember_token)
end
end
app / controllers / users_controller.rb
class UsersController < ApplicationController
before_action :signed_in_user, only: [:index, :edit, :update]
before_action :correct_user, only: [:edit, :update]
def index
#users = User.all
end
def show
#user = User.find(params[:id])
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
sign_in #user
flash[:success] = "Welcome to the Sample App!"
redirect_to #user
else
render 'new'
end
end
def edit
end
def update
if #user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to #user
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
#Before actions
def signed_in_user
unless signed_in?
store_location
redirect_to signin_url, notice: "Please sign in."
end
end
def correct_user
#user = User.find(params[:id])
redirect_to(root_path) unless current_user?(#user)
end
end
app / views / users / index.html.slim
- provide(:title, 'All users')
h1 All users
ul.users
- #users.each do |user|
li
= gravatar_for user, size: 52
= link_to user.name, user
app / helpers / users_helper.rb
module UsersHelper
# Returns the Gravatar (http://gravatar.com/) for the given user.
def gravatar_for(user, options = { size: 50 })
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
size = options[:size]
gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}"
image_tag(gravatar_url, alt: user.name, class: "gravatar")
end
end
I have not tried. but it can be something like this.
before_save { self.email = email.downcase if email}
Your error would seem to be coming from the first line of the gravatar_for method, which calls user.email.downcase, suggesting you have at least one user with a nil email address in the database.

Resources