Rails 4 - Circular dependency detected while autoloading constant Users::TodosController - ruby-on-rails-4

besides using devise for authentification w standard Devise routes.. , I added the follwoing
namespace :users do
resources :todos
end
to magane todos for the current user.
the generated routes are fine ...
users_todos GET /users/todos(.:format) users/todos#index
POST /users/todos(.:format) users/todos#create
new_users_todo GET /users/todos/new(.:format) users/todos#new
edit_users_todo GET /users/todos/:id/edit(.:format) users/todos#edit
users_todo GET /users/todos/:id(.:format) users/todos#show
PATCH /users/todos/:id(.:format) users/todos#update
PUT /users/todos/:id(.:format) users/todos#update
DELETE /users/todos/:id(.:format) users/todos#destroy
once the user is logged in , he is redirected to his todos#index list .. (users_todos_url)
def after_sign_in_path_for(resource)
....
elsif resource.is_a?(User) && Settings.permit_user_login
stored_location_for(resource) || users_todos_url
....
but then , the error is raised .... and it's stated in the log :
Started GET "/users/todos" for 127.0.0.1 at 2014-07-22 14:29:15 +0200
LoadError - Unable to autoload constant Users::TodosController, expected /Users/yves/bitbucket/railsTests/todoapp/app/controllers/users/todos_controller.rb to define it:
I have a users/todo_controller.rb
class User::TodosController < ApplicationController
..
def index
sort_order = "updated_at DESC , title"
todos = Todo.where(:user_id => current_user[:id]).order(sort_order).page params[:page]
end

Log says todo s _controller.rb.
Controller names are plural form.

Related

Rails running methods inappropriately

A rails controller defines a before_action
before_action :set_intervento, only: [ ... ]
to
def set_intervento
#intervento = Intervento.find(params[:id])
end
But my action risultati_fatturati is not listed in the only block. yet error Couldn't find Intervento with 'id'=risultati_fatturatiis being generated where Rails justifying itself as having to run the set_intervento method. What else is at work here that is launching the method?
EDIT
routes show
resources :interventos do
collection do
get :indexmio
get :indexmio_programmati
get :passati
get :non_assegnati
get :programmati
get :domani
get :domani_e_dopo
get :settimana
get :planning
get :in_corso
get :successivi
get :successivo
get :passati_da_eseguire
get :articolo_adhoc
get :calendar
post :calendarc
get :settimanale
get :chiusi
post :ripresa
get :risultati_articolos
get :risultati_ordina_articolos
get :creare_checklist
post :neuter_ddt
post :cancel_ddt
get :elenco_ddt
get :dispatcher_check
get :manager_list
get :manager_comments
post :manager_check_required
get :preventivi_attivi
get :cerca_fatturati
get :non_fatturabili
post :risultati_fatturati
get :cerca_chiusi
post :risultati_chiusi
post :duplicate_intervento
get :ordinari_chiusi
get :ordinari_aperti
end
member do
get :pdfc
get :create_pdf_rapporto
get :refresh_pause_intervento
get :refresh_close_intervento
patch :update_successivo
patch :update_ddt
patch :materials_sucessivo
patch :materials_availability
patch :preventivare
patch :esito_preventivo
patch :scaduto_preventivo
patch :ripristina_preventivo
get :dispatcher_fix
patch :dispatcher_signature
get :correzione_fattura
end
end
Translating to
indexmio_interventos GET /interventos/indexmio(.:format) interventos#indexmio
indexmio_programmati_interventos GET /interventos/indexmio_programmati(.:format) interventos#indexmio_programmati
passati_interventos GET /interventos/passati(.:format) interventos#passati
non_assegnati_interventos GET /interventos/non_assegnati(.:format) interventos#non_assegnati
programmati_interventos GET /interventos/programmati(.:format) interventos#programmati
domani_interventos GET /interventos/domani(.:format) interventos#domani
domani_e_dopo_interventos GET /interventos/domani_e_dopo(.:format) interventos#domani_e_dopo
settimana_interventos GET /interventos/settimana(.:format) interventos#settimana
planning_interventos GET /interventos/planning(.:format) interventos#planning
in_corso_interventos GET /interventos/in_corso(.:format) interventos#in_corso
successivi_interventos GET /interventos/successivi(.:format) interventos#successivi
successivo_interventos GET /interventos/successivo(.:format) interventos#successivo
passati_da_eseguire_interventos GET /interventos/passati_da_eseguire(.:format) interventos#passati_da_eseguire
articolo_adhoc_interventos GET /interventos/articolo_adhoc(.:format) interventos#articolo_adhoc
calendar_interventos GET /interventos/calendar(.:format) interventos#calendar
calendarc_interventos POST /interventos/calendarc(.:format) interventos#calendarc
settimanale_interventos GET /interventos/settimanale(.:format) interventos#settimanale
chiusi_interventos GET /interventos/chiusi(.:format) interventos#chiusi
ripresa_interventos POST /interventos/ripresa(.:format) interventos#ripresa
risultati_articolos_interventos GET /interventos/risultati_articolos(.:format) interventos#risultati_articolos
risultati_ordina_articolos_interventos GET /interventos/risultati_ordina_articolos(.:format) interventos#risultati_ordina_articolos
creare_checklist_interventos GET /interventos/creare_checklist(.:format) interventos#creare_checklist
neuter_ddt_interventos POST /interventos/neuter_ddt(.:format) interventos#neuter_ddt
cancel_ddt_interventos POST /interventos/cancel_ddt(.:format) interventos#cancel_ddt
elenco_ddt_interventos GET /interventos/elenco_ddt(.:format) interventos#elenco_ddt
dispatcher_check_interventos GET /interventos/dispatcher_check(.:format) interventos#dispatcher_check
manager_list_interventos GET /interventos/manager_list(.:format) interventos#manager_list
manager_comments_interventos GET /interventos/manager_comments(.:format) interventos#manager_comments
manager_check_required_interventos POST /interventos/manager_check_required(.:format) interventos#manager_check_required
preventivi_attivi_interventos GET /interventos/preventivi_attivi(.:format) interventos#preventivi_attivi
cerca_fatturati_interventos GET /interventos/cerca_fatturati(.:format) interventos#cerca_fatturati
non_fatturabili_interventos GET /interventos/non_fatturabili(.:format) interventos#non_fatturabili
risultati_fatturati_interventos POST /interventos/risultati_fatturati(.:format) interventos#risultati_fatturati
cerca_chiusi_interventos GET /interventos/cerca_chiusi(.:format) interventos#cerca_chiusi
risultati_chiusi_interventos POST /interventos/risultati_chiusi(.:format) interventos#risultati_chiusi
duplicate_intervento_interventos POST /interventos/duplicate_intervento(.:format) interventos#duplicate_intervento
ordinari_chiusi_interventos GET /interventos/ordinari_chiusi(.:format) interventos#ordinari_chiusi
ordinari_aperti_interventos GET /interventos/ordinari_aperti(.:format) interventos#ordinari_aperti
pdfc_intervento GET /interventos/:id/pdfc(.:format) interventos#pdfc
create_pdf_rapporto_intervento GET /interventos/:id/create_pdf_rapporto(.:format) interventos#create_pdf_rapporto
refresh_pause_intervento_intervento GET /interventos/:id/refresh_pause_intervento(.:format) interventos#refresh_pause_intervento
refresh_close_intervento_intervento GET /interventos/:id/refresh_close_intervento(.:format) interventos#refresh_close_intervento
update_successivo_intervento PATCH /interventos/:id/update_successivo(.:format) interventos#update_successivo
update_ddt_intervento PATCH /interventos/:id/update_ddt(.:format) interventos#update_ddt
materials_sucessivo_intervento PATCH /interventos/:id/materials_sucessivo(.:format) interventos#materials_sucessivo
materials_availability_intervento PATCH /interventos/:id/materials_availability(.:format) interventos#materials_availability
preventivare_intervento PATCH /interventos/:id/preventivare(.:format) interventos#preventivare
esito_preventivo_intervento PATCH /interventos/:id/esito_preventivo(.:format) interventos#esito_preventivo
scaduto_preventivo_intervento PATCH /interventos/:id/scaduto_preventivo(.:format) interventos#scaduto_preventivo
ripristina_preventivo_intervento PATCH /interventos/:id/ripristina_preventivo(.:format) interventos#ripristina_preventivo
dispatcher_fix_intervento GET /interventos/:id/dispatcher_fix(.:format) interventos#dispatcher_fix
dispatcher_signature_intervento PATCH /interventos/:id/dispatcher_signature(.:format) interventos#dispatcher_signature
correzione_fattura_intervento GET /interventos/:id/correzione_fattura(.:format) interventos#correzione_fattura
interventos GET /interventos(.:format) interventos#index
POST /interventos(.:format) interventos#create
new_intervento GET /interventos/new(.:format) interventos#new
edit_intervento GET /interventos/:id/edit(.:format) interventos#edit
intervento GET /interventos/:id(.:format) interventos#show
PATCH /interventos/:id(.:format) interventos#update
PUT /interventos/:id(.:format) interventos#update
DELETE /interventos/:id(.:format) interventos#destroy
and the controller action
def risultati_fatturati
date = params[:intervento]
#date_start = Date.civil(date["dal(1i)"].to_i, date["dal(2i)"].to_i, date["dal(3i)"].to_i)
#date_end = Date.civil(date["al(1i)"].to_i, date["al(2i)"].to_i, date["al(3i)"].to_i)
if !params[:intervento][:invoicestate_id].blank?
#interventos = Intervento.joins(:signatures).where(['signatures.created_at >= ? AND signatures.created_at <= ? AND signatures.sequence = ? AND interventos.invoicestate_id = ?', #date_start.at_beginning_of_day, #date_end.at_end_of_day, "fine", params[:intervento][:invoicestate_id]]).paginate :page => params[:page], :per_page => 100
else
#interventos = Intervento.joins(:signatures).where(['signatures.created_at >= ? AND signatures.created_at <= ? AND signatures.sequence = ?', #date_start.at_beginning_of_day, #date_end.at_end_of_day, "fine"]).paginate :page => params[:page], :per_page => 100
end
render layout: "application"
end
so the action is within a collection and does not call #intervento. This is why I find it strange.
Edit #2
Side note: attempted to remove the before_action and find the member in each action, leading to identical results. Thus there is a deeper cause.
In an attempt to view things differently and understand via triangulation, I attempted a theoretically simpler process. That of running a partial for updating each record
<%= render "stato_fatturazione", intervento: intervento %>
whose form calls a specific action, which will invoke Rails's ujs
<%= form_for stato_fatturazione_intervento_path(intervento), method: :patch, remote: true, data: {disable_with: "Aggiornando..."} do |f| %>
Alas, notwithstanding the parameters, that have the proper path for editing, rails is attempting to patch the page with the array of records, which is by definition unpatchable, and leads to the same Couldn't find Intervento with 'id'=risultati_fatturati
Started PATCH "/interventos/risultati_fatturati" for ::1 at 2017-07-31 10:52:14 +0200
Processing by InterventosController#update as JS
Parameters: {"utf8"=>"✓", "/interventos/123/stato_fatturazione"=>{"invoicestate_id"=>"3", "in_zucchetti"=>"475", "fatturato"=>"1"}, "commit"=>"Aggiorna", "id"=>"risultati_fatturati"}
The rendered HTML does confirm the target action is being intercepted by some method:
<form data-disable-with="Aggiornando..." action="/interventos/risultati_fatturati" accept-charset="UTF-8" data-remote="true" method="post">

Strong parameter does not work when i new model and controller in spree '3-0-stable' and rails 4.2

How to add new fields for spree::pre_order in Spree-3.0 + Rails4 ?
Like my old customization: ==========================
app/Controllers/spree/api/pre_order_controller
class PreOrderController < Spree::Api::BaseController
def create
#pre_order = PreOrder.new(pre_order_params)
if #pre_order.save
end
respond_with(#pre_order)
end
private
def pre_order_params
params.require(:pre_order).permit(:user_id,:is_order_created)
end
end
I Got following Error
{
"exception": "param is missing or the value is empty: pre_order"
}
Please let me know your comments.

Show virtual field in rails view

I have been using the information here (http://ngauthier.com/2013/08/postgis-and-rails-a-simple-approach.html) so that the search results in my app can be shown based on proximity.
I am listing all tasks with their associated project information - a project can have multiple tasks.
I have the following AR query in my Project controller:
#results = Task.select('tasks.*') # .select('tasks.*') required for pg_search
.joins(:project => :user)
.includes(:project => :user)
.merge(Project.enabled_only.filter_by_location(#geo).search(params[:q]))
.order_results(sort)
In my Project model I have:
scope :distance_from, ->(latitude, longitude) {
select(%{
ST_Distance(
ST_GeographyFromText(
'SRID=4326;POINT(' || projects.longitude || ' ' || projects.latitude || ')'
),
ST_GeographyFromText('SRID=4326;POINT(%f %f)')
) AS distance
} % [longitude, latitude])
}
scope :near, ->(latitude, longitude, distance_in_meters = 1000) {
where(%{
ST_DWithin(
ST_GeographyFromText(
'SRID=4326;POINT(' || projects.longitude || ' ' || projects.latitude || ')'
),
ST_GeographyFromText('SRID=4326;POINT(%f %f)'),
%d
)
} % [longitude, latitude, distance_in_meters])
}
def self.filter_by_location(geo_location)
scoped = self.all
if geo_location.present?
scoped = scoped.distance_from(geo_location[:lat], geo_location[:lng])
scoped = scoped.near(geo_location[:lat], geo_location[:lng])
end
scoped
end
I then have the following in my Task model:
scope :distance_order, -> { order('distance') }
def self.order_results(sort)
# order scopes are appended
scoped = self.all.reorder('')
# check sql for search and distance fields
search_performed = scoped.to_sql.downcase.include?(' pg_search_rank')
distance_calculated = scoped.to_sql.downcase.include?(' distance')
if sort == 'rel'
# rel,dist
scoped = scoped.search_rank_order if search_performed
scoped = scoped.distance_order if distance_calculated
else
# dist,rel
scoped = scoped.distance_order if distance_calculated
scoped = scoped.search_rank_order if search_performed
end
scoped = scoped.name_order
scoped
end
This works fine for my app to sort results by proximity.
Distance is one of the columns in the sql select produced by the AR query, along with tasks.* and distance is being used correctly to sort results but I'm not sure how to display the distance in my view.
If I do <%= result.distance.to_s %>, it says distance is an undefined method. I don't have any joy with <%= result.project.distance.to_s %> either. Whereas <%= result.task_field %> and <%= result.project.project_field %> work fine.
I haven't seen too much use of both .joins() and .includes() at the same time in the RoR world but it did allow me to reduce the number of db calls whilst still producing the correct sql select statement...in my case anyway - that's why they are both used.
Am I missing something?
Is it the complexity of my AR query causing it?
Am I missing something in my Project or Task model to allow the virtual/calculated distance field to be display-able?
Thanks
The complex structure was replaced by a database view.
More details of how to do this can be found at this tutorial (http://pivotallabs.com/database-views-performance-rails/) and in one of my other SO questions here (Connecting database view with polymorphic model in rails).

RubyMotion >> How to make a POST?

I've been checking out RestKit and the GET works
#client.get("/?amount=5", delegate:self)
Does anyone know how to make a POST and receive the result?
The docs mention that it looks something like this -
#client.post("/ask", params:#paramvar, delegate:self)
What do you encapsulate #paramvar? I have tried it as an array, hash and even nil - however, none of them have yielded any results.
Take a look at the bubble wrap library. It includes some really nice HTTP helpers.
http://bubblewrap.io/
Found an example in the RubyMotion_Cookbook.
https://github.com/IconoclastLabs/rubymotion_cookbook/tree/master/ch_8/06_sendinghttppost
class AppDelegate
def application(application, didFinishLaunchingWithOptions:launchOptions)
#window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
#window.rootViewController = RootController.new
url_string = "http://rubymotion-cookbook.herokuapp.com/post"
post_body = "bodyParam1=BodyValue1&bodyParam2=BodyValue2"
url = NSURL.URLWithString(url_string)
request = NSMutableURLRequest.requestWithURL(url)
request.setTimeoutInterval(30)
request.setHTTPMethod("POST")
request.setHTTPBody(post_body.to_s.dataUsingEncoding(NSUTF8StringEncoding))
queue = NSOperationQueue.alloc.init
NSURLConnection.sendAsynchronousRequest(request,
queue: queue,
completionHandler: lambda do |response, data, error|
if(data.length > 0 && error.nil?)
html = NSString.alloc.initWithData(data, encoding: NSUTF8StringEncoding)
p "HTML = #{html}"
elsif( data.length == 0 && error.nil? )
p "Nothing was downloaded"
elsif(!error.nil?)
p "Error: #{error}"
end
end
)
#window.makeKeyAndVisible
true
end
end
Source:
https://github.com/rubymotion/BubbleWrap
Insallation:-
in console run 'gem install bubble-wrap' or mention 'gem bubble-wrap' in Gemfile
Line to be added in 'app_delegate.rb'file(by this Bubblewrap api is available through out app):-
require 'bubble-wrap/http'
Sample code for syntax:-
BW::HTTP.get("https://api.github.com/users/mattetti", {credentials: {username: 'matt', password: 'aimonetti'}}) do |response|
p response.body.to_str # prints the response's body
end

ABPersonViewController error with RubyMotion

I am having trouble using the ABPersonViewController with RubyMotion. The error I'm getting is
Objective-C stub for message setDisplayedPerson:' typev#:^v' not precompiled. Make sure you properly link with the framework or library that defines this message.
I suspect this is due to RubyMotion not casting to the type IOS expects. I think ABPersonCreate() is returning a CFType but the displayedPerson setter is expecting it to be cast as a ABRecordRef (that's just a guess from the error messages)
Here's the sample code to see the problem (based on Apple's QuickContacts sample):
#Rakefile
$:.unshift("/Library/RubyMotion/lib")
require 'motion/project'
Motion::Project::App.setup do |app|
# Use `rake config' to see complete project settings.
app.name = 'contacts'
app.frameworks += ['AddressBook', 'AddressBookUI']
end
and
# app/app_delegate.rb
class AppDelegate
def application(application, didFinishLaunchingWithOptions:launchOptions)
window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.applicationFrame)
window.rootViewController = UINavigationController.alloc.init
window.rootViewController.wantsFullScreenLayout = true
window.makeKeyAndVisible
true
# This works
add_person('Alex', 'Rothenberg')
# This fails (is it a type casting problem?)
show_person_view_controller('Rothenberg')
end
def show_person_view_controller(name)
anError = nil
address_book = ABAddressBookCreate();
people = ABAddressBookCopyPeopleWithName(address_book, name);
person = people.first
picker = ABPersonViewController.alloc.init.autorelease
picker.personViewDelegate = self
puts "Should this be an AddressBookRef? #{person.inspect}" # => #<__NSCFType:0x8c3bec0>
picker.displayedPerson = person
# The previous line fails
puts "We never reach this line!"
self.navigationController.pushViewController(picker, animated:true)
end
def add_person(first_name, last_name)
error = nil
contact = ABPersonCreate()
ABRecordSetValue( contact, KABPersonFirstNameProperty, first_name, error )
ABRecordSetValue( contact, KABPersonLastNameProperty, last_name, error )
address_book = ABAddressBookCreate()
ABAddressBookAddRecord( address_book, contact, error )
ABAddressBookSave( address_book, error )
end
end
When you run it we are able to add to the address book in the add_person method but it fails in show_person_view_controller on the line picker.displayedPerson = person
$ rake
Build ./build/iPhoneSimulator-5.1-Development
Simulate ./build/iPhoneSimulator-5.1-Development/contacts.app
Should this be an AddressBookRef? #<__NSCFType:0x8da2900>
Objective-C stub for message `setDisplayedPerson:' type `v#:^v' not precompiled. Make sure you properly link with the framework or library that defines this message.
Any suggestions would be appreciated
This will work properly as of RubyMotion 1.12 (run sudo motion update).
Fixed a bug where performing Objective-C methods that accept
CFType objects
would crash the program (ex. [ABPersonViewController setDisplayedPerson:]).