TokBox Controller / Model Ruby - ruby-on-rails

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/)

Related

Ruby: NoMethodError in BusinessAndUnitsController#index

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

Save is not working, spree custom method

I'm working on my spree rails app, and for some reasons I'm making some custom methods. I've created a new and create methods in the ProductsController, but the last one is not working propperly, it doesn't save the data in my DB and I cant realize why.
This is my controller:
module Spree
class ProductsController < Spree::StoreController
before_action :load_product, only: :show
before_action :load_taxon, only: :index
rescue_from ActiveRecord::RecordNotFound, :with => :render_404
helper 'spree/taxons'
respond_to :html
def index
#searcher = build_searcher(params.merge(include_images: true))
#products = #searcher.retrieve_products
#taxonomies = Spree::Taxonomy.includes(root: :children)
end
#########################################by_cjdc#############################################################
def newproduct
#product = Product.new();
#render '/spree/home/newproduct'
end
def createproduct
#name = params[:product][:name];
#description = params[:product][:description];
#product = Product.new({
:id => 4,
:name => #name,
:description => #description});
#product.save();
if #product.save()
redirect_to "/tutienda", :notice => "El producto ha sido insertado";
else
render '/spree/products/newproduct'
end
end
######################################################################################################
def show
#variants = #product.variants_including_master.active(current_currency).includes([:option_values, :images])
#product_properties = #product.product_properties.includes(:property)
#taxon = Spree::Taxon.find(params[:taxon_id]) if params[:taxon_id]
end
private
def accurate_title
if #product
#product.meta_title.blank? ? #product.name : #product.meta_title
else
super
end
end
def load_product
if try_spree_current_user.try(:has_spree_role?, "admin")
#products = Product.with_deleted
else
#products = Product.active(current_currency)
end
#product = #products.friendly.find(params[:id])
end
def load_taxon
#taxon = Spree::Taxon.find(params[:taxon]) if params[:taxon].present?
end
end
end
And my methods are newproduct and createproduct. I even tried whitn and abort before #product.save to see whats in the object, and the object have the data but then the DB doesn't get it. (sorry for my bad english).
First thing you really don't need ; after every line, ror doesn't require that.
Another thing if data isn't getting save to DB then you should make sure that is there any validation failing. Now how to check which validation isn't allowing to save. To know that use bang method with save.
save -> save!
! bang method will throw an exception if any validation is getting failed.
Then just check the error and fix it.

How to use the same method in 2 controllers?

I have a Rails 2 app with an API. I versioned and optimised the controllers but there are duplicate methods. The goal is to have the common information in only one place. So I explored the following options:
redirect from routes the non-API controller, but each controller needs it's specific hooks
module inclusion. This is my favorite but there are like quite a lot of errors thrown out and very limited time to fix things up.
eval. Put all the code in one file and eval it in both places. Done this, it works but I am not pleased by this workaround.
What would be the best to go about this?
Might be some typos lurking in here but:
class GenericController < ApplicationController
def index
#objects = params[:controller].singularize.camelcase.constantize.all()
end
def show
#object = params[:controller].singularize.camelcase.constantize.find(params[:id])
end
def new
#object = params[:controller].singularize.camelcase.constantize.new
end
def edit
#object = params[:controller].singularize.camelcase.constantize.find(params[:id])
end
def create
model = params[:controller].singularize.downcase
#object = params[:controller].singularize.camelcase.constantize.new(params[model])
if #object.save
redirect_to '/'+params[:controller]
else
render :action => 'new'
end
end
def update
model = params[:controller].singularize.downcase
#object = params[:controller].singularize.camelcase.constantize.find(params[:id])
if #object.update_attributes(params[model])
redirect_to :controller => params[:controller], :action => 'index'
else
render :action => 'edit'
end
end
def destroy
if #object = params[:controller].singularize.camelcase.constantize.find(params[:id])
#object.destroy
end
redirect_to :controller => params[:controller], :action => 'index'
end
end
Specific controllers can override those implementations as needed, but:
class ProjectsController < GenericController
# done!
end
class ScenariosController < GenericController
# done!
end

Issue upgrading from Mailboxer 0.11.0 to 0.12.4

I have just updated to Mailboxer 0.12.4 and followed the instructions in the Github Readme. I had two controllers for working with the Gem
Notifications
class NotificationsController < ApplicationController
before_action :signed_in_user, only: [:create]
def new
#user = User.find(:user)
#message = current_user.messages.new
end
def create
#recepient = User.find(params[:notification][:id])
current_user.send_message(#recepient, params[:notification][:body],params[:notification][:subject])
flash[:success] = "Message has been sent!"
redirect_to user_path #recepient
end
end
Conversations
class ConversationsController < ApplicationController
before_action :signed_in_user
def index
#conversations = current_user.mailbox.conversations.paginate(page: params[:page],:per_page => 5)
end
def show
#conversation = current_user.mailbox.conversations.find_by( :id => params[:id] )
#receipts = #conversation.receipts_for(current_user).reverse!
end
end
My users model has act_as_messagable. After the update this method in my users controller is throwing an error.
uninitialized constant UsersController::Notification
the code that is highlighted is
def show
#user = User.find(params[:id])
#message = Notification.new << this line
....
end
I have tried creating a Notification object in the console and I get the same error. I have read that the update has changed the namespacing but I don't know how to change my code to account for this.
This is the closest I have found to a solution but the guy doesn't say how he fixed it
Ok I got this working I need to figure out why but it seems to be related to namespaces that were introduced in the upgrade to 0.12.4.
Step 1: Change my controllers to
mailboxer_notification_controller.rb
class MailboxerNotificationsController < ApplicationController
before_action :signed_in_user, only: [:create]
def new
#user = User.find(:user)
#message = current_user.messages.new
end
def create
#recepient = User.find(params[:mailboxer_notification][:id])
current_user.send_message(#recepient, params[:mailboxer_notification][:body],params[:mailboxer_notification][:subject])
flash[:success] = "Message has been sent!"
redirect_to user_path #recepient
end
end
Note: that the param names needed to change
mailboxer_conversations_controller.rb
class MailboxerConversationsController < ApplicationController
before_action :signed_in_user
def index
#conversations = current_user.mailbox.conversations.paginate(page: params[:page],:per_page => 5)
end
def show
#conversation = current_user.mailbox.conversations.find_by( :id => params[:id] )
#receipts = #conversation.receipts_for(current_user).reverse!
end
end
Step 2: Anywhere I accessed a method belonging to theses controllers needed to be updated with the correct namespace
def show
#user = User.find(params[:id])
#message = Mailboxer::Notification.new
....
end
Step 3: Update your config/routes.rb
SampleApp::Application.routes.draw do
resources :mailboxer_conversations
resources :mailboxer_notifications, only: [:create]
match '/sendMessage', to: 'mailboxer_notifications#create', via: 'post'
match '/conversations', to: 'mailboxer_conversations#index', via: 'get'
match '/conversation', to: 'mailboxer_conversations#show', via: 'get'
....
end
I'm not sure of the exact reasons these fixes work, I need to spend more time reading about namespaces in rails. If anyone has a good explanation feel free to add to the answer

How to escape this redirect loop?

I'm trying to make all a user's illicit attempts to see other users' show page redirect instead to their own show page.
None of my attempts in the else section of this code do the job though.
class UsersController < ApplicationController
def show
if params[:id] == current_user.id.to_s
liked_bookmark_ids = current_user.likes.pluck(:bookmark_id)
liked_bookmarks = Bookmark.where(id:liked_bookmark_ids)
liked_topic_ids = liked_bookmarks.pluck(:topic_id)
#liked_topics = Topic.where(id:liked_topic_ids).order('topics.name')
else
# redirect_to :controller => 'users', :id => current_user.id # gives a screwy url
# redirect_to user_path, :id => 6 # causes a redirect loop
# redirect_to :back # causes a redirect loop
end
end
end
What's the right way to go about it?
redirect_to user_path(current_user)
I think a better approach would be to use a filter to check if it's a request by a current user or not. You can do something like this:
class UsersController < ApplicationController
before_action :check_current_user, only: :show
def show
liked_bookmark_ids = current_user.likes.pluck(:bookmark_id)
liked_bookmarks = Bookmark.where(id:liked_bookmark_ids)
liked_topic_ids = liked_bookmarks.pluck(:topic_id)
#liked_topics = Topic.where(id:liked_topic_ids).order('topics.name')
end
private
def check_current_user
redirect_to current_user, notice: "Not authorized" if params[:id] != current_user.id.to_s
end
end

Resources