Get “wrong number of arguments” on ruby on rails - ruby-on-rails

wrong number of arguments (given 2, expected 1)
SportsController
class SportsController < ApplicationController
def index
#sport = Sport.all
#events, #errors = Bapi::Inplay.all(query)
end
private
def query
params[:query, {}]
end
end
Sport index.html.erb
<% #sports.each do |sport| %>
<% #events(:sport_id => sport.id).each_slice(2) do |events| %>
I want send each sport.id to #enevts instance variable
Edited :
When send query as hash in SportsController its work!!
class SportsController < ApplicationController
def index
#sport = Sport.all
query = {:sport_id => 1}
#events, #errors = Bapi::Inplay.all(query)
end
private
def query
params[:query, {}]
end
end
Index.html.erb
<% #sports.each do |sport| %>
<% #events.each_slice(2) do |events| %>

params is a hash and method :[] can accept only 1 argument.
def query
params[:query] || {} # Will return :query part or empty Hash if it has nothing
end

Related

Ruby on Rails, View properties

I get this error and for the life of me I can't figure out why. Help would be appreciated. :
error 3: error displayed after changes
error 4: after User.all.each do |user|
Error: Undefined method 'each' for nil: nilClass
my ruby/haml code is as follows
viewer code:
-# This file is app/views/projects/index.html.haml
%h1 All Project Tasks
= form_tag projects_path, :method => :get do
Include:
- #all_users.each do |user|
= user
= check_box_tag "users[#{user}]", 1, ("checked" if #filtered_users.find_index(user))
= submit_tag 'Refresh', :id => "users_submit"
%table#projects
%thead
%tr
%th{:class => ("hilite" if params[:sort] == "title")}= link_to "Title", {:controller => "projects", :sort => "title", :filter => #filtered_users.to_s}, :id => "title_header"
%th Task Details
%th Assigned Usertimot
%th{:class => ("hilite" if params[:sort] == "due_date")}= link_to "Due Date", {:controller => "projects", :sort => "due_date", :filter => #filtered_users.to_s}, :id => "due_date_header"
%tbody
- #projects.each do |project|
%tr
%td= project.title
%td= link_to "More about #{project.title}", project_path(project)
%td= project.user
%td= project.due_date.to_formatted_s(:long)
= link_to 'Add new project task', new_project_path
controller code:
class ProjectsController < ApplicationController
def show
id = params[:id] # retrieve project task ID from URI route
#project = Project.find(id) # look up project task by unique ID
# will render app/views/projects/show.<extension> by default
def index
#projects_users = Project.all_users
# remembered settings
if (params[:filter] == nil and params[:users] == nil and params[:sort] == nil and
(session[:filter] != nil or session[:users] != nil or session[:sort] != nil))
if (params[:filter] == nil and session[:filter] != nil)
params[:filter] = session[:filter]
end
if (params[:sort] == nil and session[:sort] != nil)
params[:sort] = session[:sort]
end
redirect_to projects_path(:filter => params[:filter], :sort => params[:sort], :users => params[:users])
else
if (params[:filter] != nil and params[:filter] != "[]")
#filtered_users = params[:filter].scan(/[\w-]+/)
session[:filter] = params[:filter]
else
#filtered_users = params[:users] ? params[:users].keys : []
session[:filter] = params[:users] ? params[:users].keys.to_s : nil
end
end
session[:sort] = params[:sort]
session[:users] = params[:users]
if (params[:sort] == "title")
if ( params[:users]or params[:filter] )
#projects = Project.find(:all, :order => "title")
end
end
if (params[:sort] == "due_date")
if ( params[:users]or params[:filter] )
#projects = Project.find(:all, :order => "due_date")
end
if (params[:sort] == nill)
if(params[:users] or params[:filter])
#projects = Project.all
end
end
end
end
def new
# default: render 'new' template
end
def create
#project = Project.create!(project_params)
flash[:notice] = "#{#project.title} was successfully created."
redirect_to projects_path
end
def edit
#project = Project.find params[:id]
end
def update
#project = Project.find params[:id]
#project.update_attributes!(project_params)
flash[:notice] = "#{#project.title} was successfully updated."
redirect_to project_path(#project)
end
def destroy
#project = Project.find(params[:id])
#project.destroy
flash[:notice] = "Project '#{#project.title}' deleted."
redirect_to projects_path
end
private
def project_params
params.require(:project).permit(:title, :description, :extended_description, :user, :due_date)
end
end
end
i understand that the spacing for haml may be a little off, just the nature of trying to format the code block thanks in advance!
viewer code:
class Project < ActiveRecord::Base
def self.all_users
allUsers = []
Project.all.each do |project|
if (allUsers.find_index(project.user) == nil)
allUsers.push(project.user)
end
end
return allUsers
end
end
You are probably getting the error on this line in your view:
#all_users.each do |user|
The reason for the error as I see it is that you don't have #all_users instantiated anywhere in your controller's index action method.
First switch #all_users to #projects_users. Also it appears that your all_users method in project.rb is overly complex and is returning nil. Try modifying project.rb to the following:
class Project < ActiveRecord::Base
def self.all_users
all.includes(:user).map(&:user).uniq
end
end
Undefined method 'each' for nil: nilClass
This error basically means you don't have any data in your variable.
In other languages, it would mean you've not delcared the variable. Because Ruby is object orientated, it will populate the variable with the nilClass class.
Many new Ruby devs are thrown by the "undefined method" exception message; it's the nilClass you have to look out for.
--
To explain the error properly, because Ruby is object orientated, every variable is actually a data object, represented by a class. In Rails, you can define these classes as models (User.find etc).
Unlike other languages, Ruby treats these objects as is -- it uses methods on them. Other languages fit data into functions, E.G PHP's each function:
#PHP
<$ each($people) $>
#Ruby
<% #people.each do |person| %>
Thus, the "no method" error basically means that Ruby cannot find the method you're calling on the nilClass. It throws developers because they think that "I have the x method on the User class", not realizing that the variable has been populated by the nilClass instead.
The short of it is that you have to either make your calls conditional, or populate the variable properly.
The error appears to be here:
#app/views/project/index.html.haml
#all_users.each do |user|
#app/controllers/projects_controller.rb
class ProjectsController < ApplicationController
def index
#projects_users = Project.all_users
end
end
You're not assigning #all_users at all
You're using an inefficient way to get "all users"
Here's what I'd do:
#app/controllers/projects_controller.rb
class ProjectsController < ApplicationController
def index
#users = Project.all_users
end
end
#app/models/project.rb
class Project < ActiveRecord::Base
scope :all_users, -> { joins(:users) } #-> this needs to be tested
end
#app/views/projects/index.haml
- #users.each do |user|
= user.name
I am pretty inexperienced with pure SQL, you'll be best referring to the joins documentation for a clearer perspective.

Parameter missing error(rails)

I am facing an error that when ever I try to call the function finalized_request it throws me an error saying "param is missing or the value is empty: finalizedeal". Since I am new to this I can't figure out what am I doing wrong(I am new to ROR).
Request_controller.rb
class RequestsController < ApplicationController
before_action :set_request, only: [:show, :edit, :update, :destroy]
# GET /requests
# GET /requests.json
def index
#categories_list = Category.getAll()
end
def active
user = session[:user]
#requests = Array.new
#tag = Array.new
#requests = Request.getRequestByUser(user)
#requests.each.with_index do |request, index|
if request != nil
#tag[index] = Array.new
request[:tag_id].each do |t|
#tag[index] << Tag.getTag(t)
end
end
end
end
# GET /requests/1
# GET /requests/1.json
def show
#user = User.getUser(#request[:user_id])
#tag = Array.new
#request[:tag_id].each do |cate|
#tag << Tag.getTag(cate)
end
end
# GET /requests/1/edit
def edit
#tag = Array.new
#request[:tag_id].each do |cate|
#tag << Tag.getTag(cate)
end
end
# POST /requests
def post_request
tags_arr = params[:tags] ;
#=begin
#categories = Array.new ;
#if tags != nil
# tags.each do |tag|
# category = Category.createCategoryIfNotExist(tag)
# if(category != nil)
# categories << category[:_id]
# end
# end
#end
#=end
tags = Array.new ;
if tags_arr != nil
tags_arr.each do |t|
tag = Tag.createTagIfNotExist(t)
if(tag != nil)
tags << tag[:_id]
end
end
end
request_data = request_params
user_id = session[:user]
request_data[:tag_id] = tags
request_data[:user_id] = user_id
#request_ = Request.createRequest(request_data)
if #request_
flash[:notice] = "Request Post successfully."
redirect_to :action => "active"
end
end
# PATCH/PUT /requests/1
# PATCH/PUT /requests/1.json
def update
#tags = params[:tags] ;
#categories = Array.new ;
#if tags != nil
# tags.each do |tag|
# category = Category.createCategoryIfNotExist(tag)
# if(category != nil)
# categories << category[:_id]
# end
# end
#end
tags_arr = params[:tags] ;
tags = Array.new ;
if tags_arr != nil
tags_arr.each do |t|
tag = Tag.createTagIfNotExist(t)
if(tag != nil)
tags << tag[:_id]
end
end
end
Rails.logger.info("RequestsParams: #{request_params.inspect}")
request_data = request_params
if request_data[:is_service] != "on"
request_data[:is_service] = "off"
end
user_id = session[:user]
request_data[:tag_id] = tags
request_data[:user_id] = user_id
if Request.updateRequest(#request,request_data)
flash[:notice] = "Request has been Edited successfully."
redirect_to :action => "active"
end
end
def delete_request ()
if Request.delete_request(params[:id])
flash[:notice] = "Request has been Deleted successfully."
render :json => "great"
end
end
# GET /requests
def finalize_request()
finalizedrequest = finalizedRequest_params
request = Request.getRequest(finalizedrequest[:title])
finalizedrequest[:title] = request[:title]
Request.delete_request(request[:_id])
FinalizedDeal.createFinalizedRequest(finalizedrequest)
redirect_to :action => "bookmark"
end
# GET /requests
def bookmark
user = session[:user]
#requests = Array.new
#tag = Array.new
#requests = Request.getRequestByUser(user)
#requests.each.with_index do |request, index|
if request != nil
#tag[index] = Array.new
request[:tag_id].each do |t|
#tag[index] << Tag.getTag(t)
end
end
end
end
# GET /requests
def bookmark_request
data = params[:d]
bookmarked_against_Request = Request.getRequest(1)
request_bookmarked = Request.getRequest(data)
request_bookmarked_2 = request_bookmarked
bookmarked_against_Request_2 = bookmarked_against_Request
Rails.logger.info("Bookmark 2: #{bookmarked_against_Request_2.inspect}")
#bookmarked_against_Request_2[:favourites] << request_bookmarked[:id]
#request_bookmarked_2[:favourites_of] << bookmarked_against_Request[:id]
#hello
#Request.updateRequest(request_bookmarked , request_bookmarked_2)
#Request.updateRequest(bookmarked_against_Request , bookmarked_against_Request_2)
redirect_to :action => "bookmark"
end
private
# Use callbacks to share common setup or constraints between actions.
def set_request
#request = Request.getRequest(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def request_params
params.require(:request).permit(:title, :description, :type , :is_service , :required_user_location , :required_product_location ,:Upper_price_range , :lower_price_range , :negotiable , :type , :tags , :category_id)
end
def finalizedRequest_params
params.require(:finalizedeal).permit(:title , :description)
end
end
finalized_deal.rb
class FinalizeDeal
include Mongoid::Document
field :deal_details, type: String
field :categories, type: Array
field :owner_user, type: MongoId
field :corsponing_user, type: MongoId
field :title, type: String
field :corresponding_product, type: String
field :meeting_date, type: String
field :date_finalized, type: String
field :description, type: String
class << self
def getRequestByUser(user_id)
requests = where(user_id: user_id).to_a
if requests
requests
end
end
def getFinzlizedRequest(req)
request = find(req)
if request
request
end
end
def createFinalizedRequest(req_data)
request = self.new(req_data)
if request.save
request
end
end
def updateFinalizedRequest(request,req_data)
if request.update(req_data)
request
end
end
def delete_FinalizedRequest(req_id)
if find(req_id).delete
true
end
end
end
end
request.html.erb
div id="form-details-modal-lbms" class="reveal-modal" data-reveal>
<h3>Enter Contract Details:</h3>
<!--<form>-->
<%= form_tag({controller: "requests", action: "finalize_request"}, method: "GET",id:"post-form-lbms" ,data: {abide: ''}) %>
<input type="hidden" id="currect_opened_req_id" value="" name="FinalizeDeal[title]"/>
<select name="meeting-id">
<option value="1">Meeting 1</option>
<option value="2">Meeting 2</option>
</select>
<label for="details-lbms">Details</label>
<textarea id="details-lbms" name="FinalizeDeal[description]"></textarea>
<button class="button tiny">
Submit
</button>
</form>
<a class="close-reveal-modal">×</a>
</div>
Please tell me what am I doing wrong. I am also posting a link to the screenshot of the error
http://tinypic.com/r/n6t8w2/8
http://tinypic.com/r/33kdq1k/8
The code is complaining because you are requiring the :finalizedeal parameter (but apparently you are not passing it along) by adding this .require(:finalizedeal) to this code:
def finalizedRequest_params
params.require(:finalizedeal).permit(:title , :description)
end
So one solution would be to simply remove the require part. Like so:
params.permit(:title , :description)
#require source
Ensures that a parameter is present.

Rails update_attribute not found

i need update a single record attribute but i can´t. alumno_id is foreign key of model 'alumno'. the code show the records and if submit 'Aceptar' in one record, need a change the attribute estado to 1
in Model
class Postulacion < ActiveRecord::Base
attr_accessible :ramo, :estado, :alumno_id
belongs_to :alumno
end
in View
<h1>Lista de Postulaciones</h1>
<% #postulaciones.each do |p| %>
<% #id = p.id %>
<%= #id %>
<p>
<td><%= Alumno.find(p.alumno_id).full_name%></td>
<td><%='=> '+ p.ramo %></td>
<td><% if p.estado == 0 %>
<%= 'Pendiente =>' %>
<%= form_tag :action => 'aceptar' do %>
<%= submit_tag 'Aceptar' %></p>
<%end%>
<%else%>
<%='=> Aceptado' %>
<%end%>
</td>
</p>
<% end %>
in controller
class ListadoController < ApplicationController
def listar
#postulaciones = Postulacion.all
respond_to do |format|
format.html
format.json { render json: #postulaciones }
end
end
def aceptar
#postulacion = Postulacion.where(id: #id).first #Edit
#postulacion.estado = 1 #Edit
#postulacion.save #Edit
redirect_to "/"
end
end
Error "undefined method `update_attribute' for []:ActiveRecord::Relation"
Thanks
With this code:
#postulacion = Postulacion.where(alumno_id: #id )
You are declaring #postulacion as a collection, not as a single instance. You can fix this by calling .first:
#postulacion = Postulacion.where(alumno_id: #id ).first
Or by using find_by instead of where:
#postulacion = Postulacion.find_by(alumno_id: #id )
One other thing - this code isn't checking for the possibility that the Postulacion instance might not exist. You should add some logic to handle this...
Your #postulacion variable holds ActiveRecord::Relation instead of single ActiveRecord object. Try:
def acceptar
#postulacion = Postulacion.find_by_alumino_id(#id)
# ...
end
or, if you'd be using Rails 4:
#postulacion = Postulacion.find_by(alumino_id: #id)

undefined method `empty?' for nil:NilClass

I display an array of hours in a dropdown field
[["09:30am", "2013-02-14 09:30:00"], ["10:00am", "2013-02-14 10:00:00"] ...
I render the array with:
<%= f.select :atime, #time_options %>
I assign the values of the array to the instance variable in the controller
def new
#time_options = Appointment.time_options
#doctor = Doctor.find(params[:doctor_id])
#appointment = #doctor.schedule.appointments.build
end
# GET /appointments/1/edit
def edit
#time_options = Appointment.time_options
#doctor = Doctor.find(params[:doctor_id])
#appointment = #doctor.appointments.find(params[:id])
end
# POST /appointments
# POST /appointments.json
def create
#time_options = Appointment.time_options
#doctor = Doctor.find(params[:doctor_id])
#appointment = #doctor.schedule.appointments.new(params[:appointment])
if #appointment.save
#send email
AppointmentMailer.appointment_confirmation(#appointment, I18n.locale).deliver
AppointmentMailer.new_appointment(#appointment, I18n.locale).deliver
redirect_to :action => 'thank_you'
else
render action: 'new'
end
end
And in the model I have defined a class method to build the array
def self.time_options
start_of_day = Time.zone.now.beginning_of_day
start_time = start_of_day + 9.hours
end_time = start_of_day + 17.hours
lunch_start = start_of_day + 13.hours
lunch_end = start_of_day + 14.hours + 30.minutes
times = []
until start_time > end_time
start_time = (start_time + 30.minutes)
unless start_time >= lunch_start && start_time < lunch_end
times << start_time
end
end
times.map{|t| [t.strftime("%I:%M%p").downcase, t.to_s(:db)] }
end
However when I submit the form, i get a undefined methodempty?' for nil:NilClass` error on:
<%= f.select :atime, #time_options %>
What I'm doing wrong?
This
<%= f.select :atime, #time_options %>
should be like this
<%= f.select :atime_id, #time_options %>
In the create method, start with the #doctor and go down the chain: schedule, then params[:appointment], until you find the nil, then figure out why it's nil. Rails.logger or pry if you're running rails s will be your friend.

block methods in ruby

I am using a block method to print a list, but it is generating error.
class MyDataListBuilder
attr_accessor :object
def initialize(object)
#object = object
end
def column (&block)
content_tag :li, block.call
end
end
and using it as
<%= my_data_list_for #leads, [" :10", "Age:30", "Contact:140", "Phone:140", "Email:180", "Company:100", ""] do |l| %>
<%= l.column do %>
<%= object.age %>
<% end %>
<% end %>
other methods are
def list_headers(args=[])
args = Array.new(args)
columns = []
args.map { |o| columns << content_tag(:li, o.split(":").first, :style=>"width:#{o.split(":").second}px;") }
content_tag(:ul, columns.join(" ").html_safe, :class=>"list-headers")
end
def my_data_list_for(object, headers=[], &block)
arr = []
object.each do |o|
arr = capture(DataListHelper::MyDataListBuilder.new(o), &block)
end
content_tag(:ol, list_headers(headers) + arr, :class=>"data-list")
end
it is generating an error and i can not figure out why:
ActionView::Template::Error (undefined local variable or method `object' for #<#<Class:0xcaa1ca0>:0xca9ebf4>):
Please help me in it.
This solves the issue.
class MyDataListBuilder
include ActionView::Helpers::TagHelper
include ActionView::Helpers::CaptureHelper
attr_accessor :object, :output_buffer
def initialize(object)
#object = object
#output_buffer = nil
end
def column (&block)
if block_given?
content_tag(:li, capture(self, &block))
else
content_tag(:li, "")
end
end
end

Resources