In RoR, in the controller, we can see lines as below:
def index
#books = Book.all
end
How can the #books = Book.all be replaced by actual sql query like select * from book
I tried something like below but I did not get it to work:
def index
sql = 'Select * from books'
#books = ActiveRecord::Base.connection.execute(sql)
end
In the browser, I am seeing this error message:
undefined method `title' for #Hash:0x00007f8dbae412f0
The find_by_sql method by Active Record is the way to go.
def index
#books = Book.find_by_sql('Select * from books')
end
reference: https://guides.rubyonrails.org/active_record_querying.html#finding-by-sql
Related
I have following create params that are passed to create!
def create_params
params.permit(
:param1,
:param2,
:param3,
:param4,
:param5
)
end
Controller
def create
something = Model.create!(create_params)
end
All the columns in the table are NOT NULL. So if i not pass any one of the param i get error something like below
Mysql2::Error: Field 'col5' doesn't have a default value: INSERT INTO `table` (`col1`, `col2`, `col3`, `col4`) VALUES ('value1', 'value2, 'value3', 'value4')
But its not giving the exact error message. How can i have it return some valid error message?
Having validations at database level like NOT NULL is a good practice.
But it is not possible, or reliable, to catch an error raised by the DB.
If you want good error messages, do the validation at ActiveRecord's level.
class Model < ActiveRecord::Base
validates :param1, :param2, :param3, :param4, :param5, presence: true
end
class ModelsController < ApplicationController
def create
model = Model.new(create_params)
if model.save # returns true or false
# ... do something
else
# ... model.errors is a collection that holds errors
model.errors
end
end
end
I kinda have 2 questions. I have following model and method to get the latest record from view. but when i try to test in console i get error undefined method or variable vCustomerDetails why i am getting the error?
Also, how do i select only one column from view?
SELECT TOP 1 HasConditionFlag FROM vCustomerDetails
WHERE vCustomerDetails.UserID = #user_id
ORDER BY EntryDate DESC
Model
module Customer
class CustomerUsage < ActiveRecord::Base
self.table_name = 'vCustomerDetails'
def self.has_condition_flag(user_id)
vCustomerDetails
.where("vCustomerDetails.UserID = #{user_id}")
.order('vCustomerDetails.EntryDate DESC')
.last
end
end
end
this one worked
def self.has_condition_flag(user_id)
CustomerUsage
.select("vCustomerDetails.HasConditionFlag")
.where("vCustomerDetails.UserID = #{user_id}")
.order('vCustomerDetails.EntryDate DESC')
.first
Remove vCustomerDetails
module Customer
class CustomerUsage < ActiveRecord::Base
self.table_name = 'vCustomerDetails'
def self.has_condition_flag(user_id)
where("vCustomerDetails.UserID = #{user_id}")
.order('vCustomerDetails.EntryDate DESC')
.last
end
end
end
to select a limited number of columns use
.select('HasConditionFlag')
I am having an issue within stupid-simple piece of ruby/mongo code below:
def initMongo
#client.new(['127.0.0.1:27017'])
end
def creatDB(name)
#database = #database.new(#client, name)
end
def creatCollection(name)
#collection = #collection.new(#database, name)
#collection.insert_one({name: 'test'})
#collection.inspect
end
With #collection.insert_one({name: 'test'}) I get :
/collection.rb:129:in write_concern': undefined method write_concern' for Mongo::Client:Class
Ruby v2.2.3 Mongo v2.2
The problem was here :
def initMongo
#client.new(['127.0.0.1:27017'])
end
Replace by :
def initMongo
#client = #client.new(['127.0.0.1:27017'])
end
I am continuing my journey in learning ruby and rails. I am currently working with the tmdb gem and trying to access and then return the results of my query.
In my MovieController, I have two methods: search_tmbd and lookup_tmdb. Here is what I have:
def search_tmdb
##movie = Tmdb::Movie.find(params[:search])
#movie = Tmdb::Movie.lookup_tmdb(params[:search])
end
def self.lookup_tmdb(title)
title = params[:search]
#movie = Tmdb::Movie.find(title)
The user inputs the query in :search. When I do the query, I get this error:
undefined method `lookup_tmdb' for Tmdb::Movie:Class.
I understand I may need to pass the values in an array, but how do I work this? This one below works for me in method search_tmdb and returns the title of the movie.
#movie = Tmdb::Movie.find(params[:search])
Change definition to this
def lookup_tmdb(title)
title = params[:search]
#movie = Tmdb::Movie.find(title)
end
and thn call from other function like this
#movie = lookup_tmdb(params[:search])
I have a module called EntityTrackerHelper. Here is the code:
module EntityTrackerHelper
def self.createUserAction(user_id, type, entity_id)
existingua = UserAction.find(:first, :conditions=> ["user_id = ? and type = ? and entity_id=?", user_id, type, entity_id])
if existingua.nil?
ua = UserAction.new
ua.user_id = user_id
ua.type = type
ua.entity_id = entity_id
ua.date = Time.now
ua.save
else
existingua.date = Time.now
existingua.save
end
end
end
It is used to track changes and user access in an entity.
It is used in a controller as follows.
require "#{Rails.root}/lib/EntityTrackerHelper"
class LessonSectionsController < InheritedResources::Base
def index
user_id = params[:user_id]
lesson_id = params[:lesson_id]
EntityTrackerHelper::createUserAction(user_id, 'LESSON', lesson_id)
lessonSections = LessonSection.find(:all, :conditions => { :lesson_id => params[:lesson_id] })
render :json => {:sections => lessonSections.as_json({:only => [:lesson_id,:id,:name]}), :error => ''}
end
end
I get the following error:
LoadError (Expected /<ProjPath>/<ProjName>/app/models/lesson.rb to define LESSON):
lib/EntityTrackerHelper.rb:12:in `createUserAction'
app/controllers/lesson_sections_controller.rb:9:in `index'
Line 12 in EntityTrackerHelper is UserAction.find...
Any idea?
Thanks
ActiveRecord will use the field type for "single table inheritance". See http://api.rubyonrails.org/classes/ActiveRecord/Base.html (subtitle: single table inheritance).
It means that when it loads the UserAction with type LESSON, ActiveRecord will try to instantiate the class LESSON which is not defined.
You probably should use another name for your type column.
You can try using
**include EntityTrackerHelper**
for more info check this link Call Module function from Controller (NoMethodError)