Ruby: NoMethodError in BusinessAndUnitsController#index - ruby-on-rails

I'm trying to created a multi-layered controller inside my app.
with the following structure :
--Business_and_units_controller (main controller)
--↳ Business_units_controller ( sub controller )
----↳ Business_managers_controller ( sub controller to Business_units_controller )
----↳ Business_divisions_controller ( sub controller to Business_units_controller )
----↳ business_units_strats_attributes_controller ( sub controller to Business_units_controller )
It's pretty complex and maybe overly?
Anyways, I've created the controller called:
business_and_units_controller.rb
with a model:
business_and_unit.rb
I've added the controller to my routes.rb (to test it and see if it works)
get '/testunit', to: 'business_and_units#index'
resources :business_and_units
After seeing if the code worked i got the following error:
NoMethodError in BusinessAndUnitsController#index
undefined method `businessandunits' for #<User:0x007f55666f2a58>
Extracted source (around line #6):
1
2
3
4 def index
6 #business_and_units = current_user.businessandunits
7
8 end
I understand that the cause of the problem is that my business_and_units is not defined. But i don't understand why it isn't defined.
Can any of you see the cause of my problem?
To summarize:
My problem: according to ruby my business_and_units_controller.rb is not defined in the index.
Goal of this post: To understand why it isn't defined.
ps: I've searched for numerous similar posts in search to the solution of my problem, but haven't been able to find a solution.
my controller file
class BusinessAndUnitsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def index
#business_and_units = current_user.business_and_units
end
def show
#business_and_units = Business_and_unit.find_by(id: params[:id])
if !#business_and_unit
raise ActionController::RoutingError.new('Not Found')
end
#user = #business_and_unit.user
end
def new
#user = User.new
#business_and_unit = Business_and_unit.new
end
def edit
#business_and_unit = Business_and_unit.find(params[:id])
end
def create
#business_and_unit = current_user.business_and_units.build(business_and_unit_params)
if #business_and_unit.save
flash[:success] = "business_and_unit created!"
redirect_to #business_and_unit
else
#feed_items = current_user.feed.paginate(page: params[:page])
render 'new'
end
end
def update
#business_and_unit = Business_and_unit.find(params[:id])
if #business_and_unit.update(business_and_unit_params)
redirect_to #business_and_unit
else
render 'edit'
end
end
def destroy
#business_and_unit.destroy
flash[:success] = "business_and_unit deleted"
redirect_to business_and_units_path
end
private
def business_and_unit_params
params.require(:business_and_unit).permit(
:corporate_strategy, :future_sale_value,
:industry, :market_focus, :business_unit,
business_units_attributes: [
:id, :business_units,
:_destroy],
business_managers_attributes: [
:id, :business_managers,
:_destroy],
business_divisions_attributes: [
:id, :business_divisions,
:business_divisions_managers,
:_destroy],
business_units_strats_attributes: [
:id, :business_units_strats,
:_destroy])
end
def correct_user
#business_and_unit = current_user.business_and_units.find_by(id: params[:id])
redirect_to business_and_units_path if #business_and_unit.nil?
end
end

The problem has nothing to do with your controller.
The error is that there is no method #businessandunits in your User model.
Based on the information you provided, I think you missed a relation definition has_many :business_and_units in your User class.
Then you will be able to call current_user.business_and_units

Related

Rails: Passing a variable from one controller to another for two forms

I have two models: one for patient and one for referral request. I've created two forms - one that allows a user to create a new patient and another that allows a user to create a referral request. A patient can have many referral requests, and and a referral request will belong to the user who created it as well as the patient it is created for.
I am having trouble figuring out how to link these forms together in a way that creates the association between the patient and the referral request being created for them by the user. I think I have to put something in the new or create actions of the referral requests controller, but I can't get anything I've tried to work.
Any help appreciated for a rookie!
Patients Controller:
class PatientsController < ApplicationController
def new
#patient = current_user.patients.build
end
def create
#patient = current_user.patients.build(patient_params)
if #patient.save
flash[:success] = "Patient Created!"
redirect_to '/referral_requests/new'
else
Rails.logger.info(#patient.errors.inspect)
render 'patients/new'
end
end
private
def patient_params
params.require(:patient).permit(:age, :user_id, insurance_ids: [], gender_ids: [], concern_ids: [], race_ids: [])
end
end
Referal Requests Controller:
class ReferralRequestsController < ApplicationController
before_action :logged_in_user, only: [:show, :index, :new, :create, :edit, :update, :destroy]
def index
if logged_in?
#referral_request = current_user.referral_requests.build
#feed_items = current_user.feed.paginate(page: params[:page])
else
#feed_items =[]
end
end
def create
#referral_request = current_user.referral_requests.build(referral_request_params)
if #referral_request.save
flash[:success] = "Referral Request Created!"
render 'referral_requests/index'
else
Rails.logger.info(#referral_request.errors.inspect)
#feed_items = []
render 'static_pages/home'
end
end
def destroy
end
def new
#referral_request = current_user.referral_requests.build if logged_in?
end
private
def referral_request_params
params.require(:referral_request).permit(:content, concern_ids: [],
insurance_ids: [], race_ids: [], language_ids: [], gender_ids: [])
end
end
you need to pass in the patient_id in your redirect in the create action of PatientsController.
redirect_to '/referral_requests/new'
should become
redirect_to new_referral_request_path(patient_id: #patient.id)
then in ReferralRequestsController you can associate the newly built referral_request with the patient
def new
#patient = Patient.find(params[:patient_id])
#referral_request = current_user.referral_requests.build(patient: #patient) if logged_in?
end
Then in your referral_requests/new.html.erb form you can add a hidden_field_tag
form_for(#referral_request) do |f|
f.hidden_field :patient_id
.....
end
which will then add patient_id to into the form params and pickup the patient_id that got associated in the new action of the controller
You will need to add :patient_id into your referral_request_params method as well

Rails throwing error instead validating

I am building a fairly straightforward Rails 5 application. You create "Movies," and then can create "Reviews" for those movies. Rails is doing something odd. I have my application set up so instead of a "new" action and a corresponding view, I have the form to create new movies in a modal contained in the application.html.erb file. I then provide #newmovie = Movie.new in the controller for all the movie views, so the data is available everywhere.
I have validations for the movie object setup like this:
class Movie < ApplicationRecord
has_many :reviews
validates :title, :director, :poster, :synopsis, presence: true
end
When I fill out the form to create a new movie in the modal on my index view and intentionally leave fields blank (to trigger the validation), I get this:
instead of the form simply not accepting the input. What's going on here? I can't have this error happening like this. Previously, I had a "new" view. This did not happen in the previous setup. Help!
Here is my entire movies controller:
class MoviesController < ApplicationController
before_action :find_movie, only: [:show, :edit, :update, :destroy ]
before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy]
before_action :find_newmovie, only: [:show, :index, :new, :edit]
def show
#reviews = #movie.reviews.all.order(created_at: :desc).paginate(:page => params[:page], :per_page => 3)
#review = Review.new
if #movie.reviews.blank?
#average_review = 0
else
#average_review = #movie.reviews.average(:rating).round(2)
end
end
def index
#movies = Movie.all.order(title: :asc).paginate(:page => params[:page], :per_page => 3)
#newmovie = Movie.new
end
def new
#movie = Movie.new
end
def create
#movie = Movie.create(movie_params)
#movie.user_id = current_user.id
if #movie.save
flash[:success] = "Your movie was created!"
redirect_to root_path
else
flash[:danger] = "There was a problem with your request"
render :new
end
end
def edit
end
def update
if #movie.update(movie_params)
flash[:success] = "Your movie was updated"
redirect_to movie_path
else
flash[:danger] = "There was a problem with your request"
end
end
def destroy
if #movie.destroy
flash[:success] = "Your movie was removed"
redirect_to movies_path
else
flash[:danger] = "There was a problem with your request"
render :index
end
end
private
def movie_params
params.require(:movie).permit(:title, :director, :poster, :synopsis, :user_id)
end
def find_movie
#movie = Movie.find(params[:id])
end
def find_newmovie
#newmovie = Movie.new
end
end
In new action of movies_controller, you missed to initalize the instance variable #newmovie.
add below code in movies_controller:
class MoviesController < ApplicationController
def new
#newmovie = Movie.new
end
...
end

TokBox Controller / Model Ruby

UPDATE: I have solved the NilClass issue! Thanks!
Now I am having a problem with:
unknown attribute 'sessionId' for Room.
SOLVEDI am currently having some issues where my code is telling me I have an error of "undefined method `create_session' for nil:NilClass" on line 9. I will provide the files.
This is the specific line:
#new_room = Room.new(strong_param)
rooms_controller.rb
class RoomsController < ApplicationController
require "opentok"
before_filter :config_opentok,:except => [:index]
def index
#rooms = Room.where(:public => true).order("created_at DESC")
#new_room = Room.new
end
def create
session = #opentok.create_session :media_mode => :routed
params[:room][:sessionId] = session.session_id
#new_room = Room.new(strong_param)
respond_to do |format|
if #new_room.save
format.html { redirect_to(“/party/”+#new_room.id.to_s) }
else
format.html { render :controller => ‘rooms’, :action => “index” }
end
end
end
def party
#room = Room.find(params[:id])
#tok_token = #opentok.generate_token #room.sessionId
end
private
def config_opentok
if #opentok.nil?
#opentok = OpenTok::OpenTok.new ########, "#########################################"
end
end
def strong_param
params.require(:room).permit(:name,:sessionId)
end
end
rooms.rb (Models)
class Room < ActiveRecord::Base
end
I've tried several different modifications to these files to make my program work. I can get the listing page to work but once I try and actually create a new room, I receive this error message.
Look forward to any advice you can provide.
You are missing the before_filter :config_opentok,:except => [:index] line from the blog post in your previous post (https://railsfornovice.wordpress.com/2013/01/01/video-chatting-in-ruby-on-rails/)

Rails 4: One-to-one controller issue

I'm building an app which consists on sharing résumés. I am using Devise gem. Each user is able to create only one résumé. I made the models and and their relations. Resume belongs_to User and User has_one 'Resume'.
After making the views, I wanted to test my app but I got the error: undefined methodbuild' for nil:NilClass`
Here is my ResumeController and my routes.rb
class ResumeController < ApplicationController
before_action :find_resume, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:show]
def show
# #resume = Resume.find_by(params[:id])
end
def new
#resume = current_user.resume.build
end
def create
#resume = current_user.resume.build(resume_params)
if #resume.save
redirect_to #resume, notice: "resume was successfully created"
else
render 'new'
end
end
def edit
end
def update
if #resume.update(pin_params)
redirect_to #resume, notice: "resume was successfully updated"
else
render 'edit'
end
end
def destroy
#resume.destroy
redirect_to root_path
end
private
def resume_params
params.require(:resume).permit(:title, :description)
end
def find_resume
#resume = resume.find(params[:id])
end
end
Routes.rb
Rails.application.routes.draw do
devise_for :users
resources :resume, except: [:index]
get 'static_pages/index'
root to: "static_pages#index"
end
I just want the user to be able to create only one Resume and then he will be able to share it.
Update: After following messanjah's answer there was another error coming from the _form.html.erb: undefined method resumes_path' for #<#<Class:0x00...>. Here is the gist with forms and model: goo.gl/XvW2LH So you can see all the files closely.
Without more knowledge of where the error is happening, I can only suggest some areas that might be suspect.
To build a has_one relationship, you must use the build_*association* constructor.
def new
#resume = current_user.build_resume
end
def create
#resume = current_user.build_resume(resume_params)
end

Keep Receiving an "Unknown attribute=user_id" error

First time poster, long time lurker here. I have a Users model and controller for a little video game application for Rails that I'm currently making. So I've read a couple of answers on here regarding this issue, but none of the answers really seem to have helped me. People have suggested adding a "user_id" column to my Users table, but my point of contention is, I thought the "user_id" was automatically made in Rails? Even if I use a user.inspect, I still see a user_id=7show up on the page. However, I still get the unknown attribute error when attempting to create a game and assign to the current user. Any help would be most appreciated in pinpointing the cause and solution to this. Thanks!
app/controllers/users_controller.rb:
class UsersController < ApplicationController
skip_before_filter :require_authentication, only: [:new, :create]
def index
#users = User.all
end
def show
end
def new
#user = User.new
end
def edit
#user = current_user
end
def create
#user = User.create!(user_params)
session[:user_id] = #user.id
redirect_to users_path, notice: "Hi #{#user.username}! Welcome to DuckGoose!"
end
def update
current_user.update_attributes!(user_params)
redirect_to users_path, notice: "Successfully updated profile."
end
def destroy
#user = User.find(params[:id])
#user.destroy
redirect_to users_url, notice: 'User was successfully destroyed.'
end
private
def user_params
params.require(:user).permit(:username, :firstname, :lastname, :email, :password, :password_confirmation)
end
end
app/config/routes.rb:
NkuProject::Application.routes.draw do
resources :users do
resources :games
end
resources :sessions
resources :games
get "sign_out", to: "sessions#destroy"
get "profile", to: "users#edit"
root to: "sessions#new"
end
app/controllers/games_controller.rb
class GamesController < ApplicationController
def new
#game = Game.new
end
def index
#games = Game.all
end
def destroy
#game = Game.find(params[:id])
#game.destroy
redirect_to games_url, notice: 'Game was successfully deleted.'
end
def create
#game = current_user.games.build(game_params)
if #game.save
redirect_to #game, notice: "Game successfully added"
else
render :new
end
end
def show
#game = Game.find(params[:id])
end
private
def game_params
params.require(:game).permit!
end
end
app/controllers/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 :require_authentication
def current_user
#current_user ||= User.find_by(id: session[:user_id]) if session[:user_id].present?
end
helper_method :current_user
def require_authentication
if current_user
true
else
redirect_to new_session_path
end
end
end
I'm sure I'm missing some code to put in for reference, but if I need anything else please let me know.
Looking at the way your controller actions are defined, I can safely say that User and Game have a 1-M relationship, i.e.,
class User < ActiveRecord::Base
has_many :games
end
class Game < ActiveRecord::Base
belongs_to :user
end
Now, based on that games table must have a field named user_id. Rails is not going to create it for you unless you specify it. You need to add field user_id in games table by creating a migration for the same. Right now, it doesn't seem like you have user_id foreign_key field in games table. Hence, the error while saving games record.

Resources