I had got a task to select search the students those name start with param value and city in the selected value.How can i set in ruby on rails?
i did like this but this is not working
controller
def list
studentcount=Student.count()
puts studentcount
#studentname = Student.where("name name1 AND city = :cityId1",
{:name1 => params[:name], :cityId1 => params[:cityId]})
puts 'studentname'
puts #studentname.inspect
#students = Student.limit(params[:jtPageSize]).offset(params[:jtStartIndex]).order(params[:jtSorting])
#jtable = {'Result' => 'OK','Records' => #students.map(&:attributes), :TotalRecordCount => studentcount}
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #jtable}
end
end
Try:
#studentname = Student.where("name LIKE :name1 AND city = :cityId1",
{:name1 => "#{params[:name]}%", :cityId1 => params[:cityId]})
This is a rather dirty solution, but pure ARel cannot handle this case the way you desire. You might want to try the Sqeel gem.
Try
#studentname = Student.where("name LIKE ? AND city = ?", "#{params[:name]}%", params[:cityId])
there is a error in your methods, it should be like this
#studentname = Student.where("name = :name1 AND city = :cityId1",
{:name1 => params[:name], :cityId1 => params[:cityId]})
Related
This is my ruby file with hash:
book.rb
class Book
attr_accessor :title, :author, :language, :classification, :isbn, :book_id, :borrow_status
def initialize(title, author, language, classification, isbn, book_id, borrow_status)
#title = title
#author = author
#language = language
#classification = classification
#isbn = isbn
#book_id = book_id
#borrow_status = borrow_status
end
def bookid
#book_id
end
def booklist
#title = #title.split(/ |\_|\-/).map(&:capitalize).join(" ")
#author = #author.split(/ |\_|\-/).map(&:capitalize).join(" ")
#language = #language.capitalize
#isbn.to_s
#book_id.to_s
{
:Title => #title,
:Author => #author,
:Language => #language,
:Classification => #classification,
:ISBN => #isbn,
:Book_ID => #book_id,
:Status => #borrow_status,
}
end
end
for now, I already have five key-value pair for this hash, they are in ruby file named top.rb:
$books1 = Book.new("lonely planet: ireland","damian harper","english","tourism",9781786574459,1,"available")
$books2 = Book.new("ninteen eighty four","george orwell","english","literature",9781374677817, 2,"available")
$books3 = Book.new("japanese in 30 days","naomi ono","japanese","education",9787928365729,3,"available")
$books4 = Book.new("brand famous: how to get everyone talking about your business","linzi boyd","english","business",9780857084903,4,"borrowed")
$books5 = Book.new("SQL in 10 mins","ming zhong, xiaoxia liu","chinese","hi tech",9787115313980,5,"unavailable")
and using the method below to output the result:
def status
bookstatus = gets.chomp.to_s
if bookstatus == "status"
puts "Status:" + "\n" + "#{$books1.booklist[:Book_ID]}: #{$books1.booklist[:Title]}: #{$books1.booklist[:Status]}"
puts "#{$books2.booklist[:Book_ID]}:#{$books2.booklist[:Title]}: #{$books2.booklist[:Status]}"
puts "#{$books3.booklist[:Book_ID]}:#{$books3.booklist[:Title]}: #{$books3.booklist[:Status]}"
puts "#{$books4.booklist[:Book_ID]}:#{$books4.booklist[:Title]}: #{$books4.booklist[:Status]}"
puts "#{$books5.booklist[:Book_ID]}:#{$books5.booklist[:Title]}: #{$books5.booklist[:Status]}"
else
puts "error"
end
end
For now, I am going to add some more value, I am going to let user enter the information of books (e.g., title = gets.chomp.to_s), and make a new key-value pair for the book added.
As I know, add new key-value pair to ruby is like below:
my_hash = {:a => 5}
my_hash[:key] = "value"
But, the hash in book.rb does not have any name, I tried to give it a name like
book_list = {
:Title => #title,
:Author => #author,
:Language => #language,
:Classification => #classification,
:ISBN => #isbn,
:Book_ID => #book_id,
:Status => #borrow_status,
}
it will output error.
My question is, I would like to know how can I add a new key-value pair to the hash in my ruby file, which has no name?
Thanks.
Changing the booklist method to this will solve your immediate problem:
def booklist
#booklist ||= {
:Title => #title.split(/ |\_|\-/).map(&:capitalize).join(" "),
:Author => #author.split(/ |\_|\-/).map(&:capitalize).join(" "),
:Language => #language.capitalize,
:Classification => #classification,
:ISBN => #isbn.to_s,
:Book_ID => #book_id.to_s,
:Status => #borrow_status,
}
end
Now you can do booklist[:Xyz] = 'xyz'.
The code in your question has so many "Hello world!" -level mistakes, that it appears you still seem to have a bit to learn about Ruby basics, such as using variables, the difference between #isbn, isbn, $isbn, ISBN, or ##isbn, etc.
There are better "learn ruby" tutorials online than I'm ready to start here, so my answer is probably not very helpful.
I am new to Ruby. I have the below code in my controller.
Desired Behaviour:-
I want to display the validation error string on my views on edit page. So I am putting those errors in a variable. When validation fails then I want to use that variable in my edit method, so that I can display that on my edit page view.
Observed behavior:-
There is a variable #vpinerr in create method. I want to use that variable in edit method. I have tried to use the class variable (##vpinerr) and initialized it with an empty string (##vpinerr = "") then the value of this variable becomes empty in edit method.
require 'rho/rhocontroller'
require 'helpers/browser_helper'
class LeadController < Rho::RhoController
include BrowserHelper
# GET /Lead
def index
#leads = Lead.find(:all)
render :back => '/app'
end
# GET /Lead/new
def new
#lead = Lead.new
render :action => :new, :back => url_for(:action => :index)
end
def create
# Update
if Lead.find(#params['id'])
#lead = Lead.find(#params['id'])
# array of objects
#leadadd = LeadAddress.find(:all,
:conditions => {:parentKey => #lead.object}
)
#leadcon = LeadContact.find(:all,
:conditions => {:parentKey => #lead.object}
)
#hash of hashes
leadaddressArray = #params['leadaddress']
arr1 = #leadadd.count - 1
for i in 0..arr1
j=i.to_s
#leadaddHash = #leadadd[i]
leadaddressHash = leadaddressArray[j]
if leadaddressHash['removed'] == "1"
singleadd = LeadAddress.find(:first,
:conditions => {:object => leadaddressHash['object']}
)
singleadd.destroy if singleadd
else
#validation
vpin = leadaddressHash['pincode']
#validation check
if vpin =~ /^[[:digit:]]+$/
#leadaddHash.update_attributes(leadaddressHash) if #leadaddHash
else
err = 1
#vpinerr = "Pincode is invalid"
end
end
end
leadconArray = #params['leadcontact']
arr2 = #leadcon.count - 1
for k in 0..arr2
z=k.to_s
#leadconHash = #leadcon[k]
leadContact = leadconArray[z]
if leadContact['removed'] == "1"
singlecon = LeadContact.find(:first,
:conditions => {:object => leadContact['object']}
)
singlecon.destroy if singlecon
else
#leadconHash.update_attributes(leadContact) if #leadconHash
end
end
#lead.update_attributes(#params['lead']) if #lead
if err == 0
redirect :action => :index
else
redirect :action => :edit, :id => #lead.object, :vpin =>#vpinerr
end
else
# Create
err = 0
# validation
vlead = #params['lead']
vfirstname = vlead['firstname']
vlastname = vlead['lastname']
vage = vlead['age']
#validation check
if (vfirstname =~ /^[[:alpha:][:blank:]]+$/) and (vlastname =~ /^[[:alpha:][:blank:]]+$/) and (vage =~ /^[[:digit:]]+$/)
#lead = Lead.create(#params['lead'])
#key = #lead.object
else
err = 1
#basicerr = "Basic Details are invalid"
end
if #params['leadaddress']
leadaddressArray = #params['leadaddress']
arrcount = leadaddressArray.count
for i in 1..arrcount
j=(i-1).to_s
leadaddressHash = leadaddressArray[j]
#validation
vpin = leadaddressHash['pincode']
#validation check
if vpin =~ /^[[:digit:]]+$/
#leadAdd = LeadAddress.create(leadaddressHash)
#leadAdd.parentKey = #key
#leadAdd.save()
else
err = 1
#vpinerr = "Pincode is invalid"
end
end
end
if #params['leadcontact']
leadconArray = #params['leadcontact']
arrcount2 = leadconArray.count
for k in 1..arrcount2
h=(k-1).to_s
leadconHash = leadconArray[h]
#validation
vhome = leadconHash['home']
vmobile = leadconHash['mobile']
vemail = leadconHash['email']
#validation check
if (vhome =~ /^[[:digit:]]+$/) and (vmobile =~ /^[[:digit:]]+$/) and (vemail =~ /\A([\w+\-]\.?)+#[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i)
#leadcontact = LeadContact.create(leadconHash)
#leadcontact.parentKey = #key
#leadcontact.save()
else
err = 1
#contacterr = "Contact Details are invalid"
end
end
end
if err == 0
redirect :action => :index
else
redirect :action => :edit, :id => #lead.object
end
end
end
# GET /Lead/{1}
def show
#lead = Lead.find(#params['id'])
#leadadd = LeadAddress.find(:all,
:conditions => {:parentKey => #lead.object}
)
#leadcontact = LeadContact.find(:all,
:conditions => {:parentKey => #lead.object}
)
if #lead
render :action => :show, :back => url_for(:action => :index)
else
redirect :action => :index
end
end
# GET /Lead/{1}/edit
def edit
#lead = Lead.find(#params['id'])
#leadaddress = LeadAddress.find(:all,
:conditions => {:parentKey => #lead.object}
)
#leadcontact = LeadContact.find(:all,
:conditions => {:parentKey => #lead.object}
)
#vpinerr2 = #vpinerr
if #lead
render :action => :new, :back => url_for(:action => :index)
else
redirect :action => :index
end
end
end
Variables with a prepending # are considered as instance variables and are available in a class's instance. Your controller is a class and with every request, Rails instantiates a new controller instance. In that sense, when you make a request to the create action, a new instance is created and #vpinerr is set in the instance. When you redirect the user to the edit action, its a new request and a new controller instance is instantiated. Since the instances from create action and edit actions are different, you won't have the value of #vpinerr in the edit action.
You have alternatives.
Class-level variables.
Class-level variables are set on the class and are available in all instances. Any variable prepended with ## are class variables. Change to ##vpinerr everywhere instead of #vpinerr.
This would be wrong to use in your case because, you could want it to be different for each user but using class variable will keep the value for other users too until its changed. Read about class variables: http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby
Session variables.
Session variables are used to save variables within a session. They can be shared between controllers too. To set a session variable session[:vpinerr] = "Some error" and to use it, you can simple call session[:vpinerr].
I'm getting an error expected ':' after property name in object at line 1 column 15 how can I get rid of '=>'? when I replace "=>" by ":" in the to_json methods I'm getting an error syntax error, unexpected ':', expecting =>
require 'json'
class Province
attr_accessor :provOrigine, :destination, :total,
:q1, :q2, :q3, :q4
def initialize(line)
#provOrigine = line.split(';').first.split(",").first
#destination = line.split(';').at(1).split(',').first
#q1 = (line.split(';').at(4)).to_i
#q2 = (line.split(';').at(5)).to_i
#q3 = (line.split(';').at(6)).to_i
#q4 = (line.split(';').at(7)).to_i
end
def to_json
{'provOrigine' => #provOrigine.to_s, 'destination' => #destination.to_s, 'q1' => #q1.to_s, 'q2' => #q2.to_s, 'q3' => #q3.to_s, 'q4' => #q4.to_s}
end
end
...
prov_instances = contains All the instances of Province
...
File.open("file_json_complete.json", "w") do |f|
prov_instances.each do |n|
f.write(n.to_json)
end
end
this is the result I'm getting
{"provOrigine"=>"Alberta", "destination"=>"Terre-Neuve-et-Labrador", "q1"=>"777", "q2"=>"1089", "q3"=>"553", "q4"=>"474"}{"provOrigine"=>"Alberta", "destination"=>"Nunavut", "q1"=>"24", "q2"=>"70", "q3"=>"29", "q4"=>"29"}{"provOrigine"=>"Alberta", "destination"=>"Île-du-Prince-Édouard", "q1"=>"116", "q2"=>"69", "q3"=>"150", "q4"=>"64"
}
and there is no commas between each object?
You'd need to add the commas yourself. f.write(n.to_json) is going to write out a single Province. It has no way to know you're going to keep writing more and need a comma.
Is there a reason you can't do this instead?
File.open('file_json_complete.json', 'w') do |f|
f.puts prov_instances.to_json
end
I needed to take the hash {} and cast it to_json in order to create a json string
class Province
def to_json(*a)
{'provOrigine' => #provOrigine.to_s,
'destination' => #destination.to_s,
'q1' => #q1.to_s, 'q2' => #q2.to_s,
'q3' => #q3.to_s, 'q4' => #q4.to_s
}.to_json(*a)
end
end
I don't need to loop thought each instances. I could take the object Array and cast it to_json
File.open("file_json_complete.json", "w") do |f|
f.write(prov_instances.to_json)
end
i'm working on this script -> http://www.redmine.org/plugins/default_members <- by Sajin Andrei
I've completely modified the hook to suite my needs, but i realized that it actually adds every single user that is member of the defined group.
what i want to do is, instead, add the entire group to the project, so that if i add anyone else to the same group i'll not have to update every project.
this is my code:
# Debuggin [Default: commented/disabled]
#require 'logger'
class DefmembersHook < Redmine::Hook::ViewListener
def controller_projects_new_after_save(context={ })
#log = Logger.new('/usr/local/share/redmine/log/plugin.log')
params = context[:params]
project = context[:project]
roles = Role.find_all_givable
setting_group = Setting.plugin_redmine_default_members[:group] ? Setting.plugin_redmine_default_members[:group] : 'Manager'
groups ||= setting_group.split(",")
groups.each do |gp|
#log.error "gp: #{gp}"
group = Group.find(:first, :conditions => ["LOWER(lastname) = ?", gp.to_s.downcase])
#log.error "group: #{group}"
users = User.active.in_group(group).all(:limit => 100)
users.each do |user|
if user[:lastname] != 'Admin' && user[:lastname] != 'Anonymous'
#log.error "inizio per #{user}"
rs = Role.find_by_name(group.to_s)
#log.error "rs: #{rs}"
m = Member.new(:user => user, :roles => [rs])
project.members << m
#log.error "fine per #{user}"
end
end
end
end
end
and is actually working as intended by Sajin Andrei, adding single users from a group.
i want to do something like this
m = Member.new(:group => group, :roles => [rs])
project.members << m
but it doesn't work (obviously)...
hope someone can help
found the solution:
# Modificata da CARLO RUGGIERO per RETINA
# Permette di aggiungere interi gruppi ad un progetto in automatico!
class DefmembersHook < Redmine::Hook::ViewListener
def controller_projects_new_after_save(context={ })
params = context[:params]
project = context[:project]
#roles = Role.find_all_givable
setting_group = Setting.plugin_redmine_default_members[:group] ? Setting.plugin_redmine_default_members[:group] : 'Manager'
groups ||= setting_group.split(",")
groups.each do |gp|
group = Group.find(:first, :conditions => ["LOWER(lastname) = ?", gp.to_s.downcase])
rs = Role.find_by_name(group.to_s)
project.members << Member.new(:principal => group, :roles => [rs])
end
end
end
the problem was that the :user tag only accepts user elements
changing it to :principal i've got it to work
m = Member.new(:principal => group, :roles => [rs])
project.members << m
hope that someone find this usefull
I have a task to list students' details. I want to perform searching based on name and city. If cityId==0 and name='', then I want to list all my student details. How can I do this? I did this in a wrong way. The controller is:
if(Student.where(params[:cityId])==0)
studentcount = Student.count()
#students = Student.limit(params[:jtPageSize]).offset(params[:jtStartIndex]).order(params[:jtSorting])
#jtable = {'Result' => 'OK','Records' => #students.map(&:attributes), :TotalRecordCount => studentcount}
else
studentcount = Student.where("name LIKE ? AND city = ?", "%#{params[:name]}%", params[:cityId]).count()
#students = Student.where("name LIKE ? AND city = ?", "%#{params[:name]}%", params[:cityId]).limit(params[:jtPageSize]).offset(params[:jtStartIndex]).order(params[:jtSorting])
#jtable = {'Result' => 'OK','Records' => #students.map(&:attributes), :TotalRecordCount => studentcount}
Your condition should look like this:
if( Student.where(:cityId => params[:cityId]).count == 0 )
The if-statement you have tests a ActiveRecord::Relation and an Integer for equality which will never be true
if User.where(city_id: params[:cityId]).empty?