mardi 31 mars 2015

Search bar not working on some pages Sunspot Solr

I added a search bar to my header, so every page in the application has one. However, the search bar only works on the home page and index pages. When I go to my contact page (just an example) it doesn't work. I have tried redirecting to my search URL, but nothing seems to work. Any suggestions?


search_controller.rb (controller)



class SearchController < ApplicationController

def index
@search = Sunspot.search [Dairy, Drink] do
fulltext params[:search]
end

if @search.results.any?
@results = @search.results
else
return redirect_to request_path
end
end

end


search.rb (model)



class Search < ActiveRecord::Base

attr_accessible :title

searchable do
autosuggest :search_title, :using => :title
end
end


_searchbarheader.html.erb (search bar view)



<%= form_tag search_index_path, :method => :get do %>
<%= text_field_tag :search, params[:search], style:"width:300px; height:30px;" %>
<%= submit_tag "Search!", :name => nil, class: "btn btn-default"%>
<% end %>


_header.html.erb (header view)



<div class="container-fluid">
<%= render 'layouts/brand' unless @skip_brand %>
<form class="navbar-form navbar-left">
<%= render 'layouts/searchbarheader' unless @skip_header %>
</form>

<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<% if user_signed_in? %>
<li><%= link_to current_user.name%></li>
<li><a class="glyphicon glyphicon-cog" href="<%=edit_user_registration_path%>"></a></li>
<li><%= link_to "Logout", destroy_user_session_path, method: :delete %> </li>
<%else%>
<li><%= link_to "Login", new_user_session_path %></li>
<li><%= link_to "Sign up", new_user_registration_path %></li>
</ul>
<%end%>
</div>


My searchbar is rendered into the header, and header rendered into the app. Thank you for any help. Still learning how rails and solr works together.


Rails scope using has_many association

I have three models defined as below:



class Parent < ActiveRecord::Base
has_many :kids
has_many :restrictions

def has_valid_restriction?
self.restrictions.where(:type => 1).size > 0
end
end

class Kid < ActiveRecord::Base
belongs_to :parent
has_many :restrictions

scope :valid, -> {
includes(:restrictions).where("restriction.type = 1")
}
end

class Restriction < ActiveRecord::Base
belongs_to :restricted_object #this can be kid or parent
end


Kid has a scope called 'valid' which chooses the Kids having a restriction with type 1. I want to add a similar scope to Parent which chooses Parents which either have a restriction of type one or a valid Kid (i.e. a Kid with restriction of type 1).


How can I create such a scope?


rails 2 debug connection reset by peer error

I have multiple apps running in the same server.


I have this issue with this one application which is rails 2 and ruby 1.8.x which does the following:




  1. The users Upload a spreadsheet with some company information and username though the UI.




  2. Once the file is uploaded it hits a external service to create client certificates based on the information provided.




  3. It then stores the certificate information in the database.




The problem I am having is sometimes the controller just errors out with the following:



"Connection Reset by peer"



Note this is an internal app and will be used by 2 people at the most.


And the error does not seem to happen everytime. It happens every now and then and the size of the file does not seem to be the issue.


Sometimes it goes through without any error for large files and sometimes it fails on small files. Sometimes the same file upload passes the second time I looked at the web service logs and it does not have any errors.


I looked at the web logs and found the following:



4.0.10/lib/phusion_passenger/rack/thread_handler_extension.rb:77:in process_request'/opt/ruby-1.9.3/lib/ruby/gems/1.9.1/gems/passenger-4.0.10/lib/phusion_passenger/request_handler/thread_handler.rb:140:inaccept_and_process_next_request'/opt/ruby-1.9.3/lib/ruby/gems/1.9.1/gems/passenger-4.0.10/lib/phusion_passenger/request_handler/thread_handler.rb:108:in main_loop'/opt/ruby-1.9.3/lib/ruby/gems/1.9.1/gems/passenger-4.0.10/lib/phusion_passenger/request_handler.rb:441:in start_threads'/opt/ruby-1.9.3/lib/ruby/gems/1.9.1/gems/passenger-4.0.10/lib/phusion_passenger/request_handler.rb:435:in `initialize'/opt/ruby-1.9.3/lib/ruby/gems/1.9.1/gems/passenger-4.0.10/lib/phusion_passenger/request_handler.rb:435 Redirected to http://my-url?flash%5Berror%5D=Unable+to+process+uploaded+file.+Please+make+sure+you+provided+a+valid+excel+%28.xls%29+file.+Detailed+error+message%3A+Connection+reset+by+peer



Is there something on the passenger apache config that I might be able to fix and test?


Maybe increase the PassengerMaxPoolSize & PassengerPoolIdleTime?


I dont want to play with the config without understanding it well.


glib2 failing to compile for gem install dependency with cairo and poppler

We are using Cairo and Poppler c libraries for come QR code stuff, and on unix/linux/ubuntu all is fine in production and test systems. Developers on Mac OS X constantly have issue with these gems, like when we upgrade Mac OS x from 10.9 to 10.10, or upgrade ruby from 1.9 to 2.1.


Our engineers are currently stuck on the latest issue with Ruby 2.1 Rail 3.2.21 and Mac OS x 10.10. We have RVM, HomeBrew, MacPorts all setup. I suspect issue with different gcc versions apple offers vs what mac ports installs...we have tried toggling symlinks, but are not really sure....


Any ideas/thoughts welcome, thank you!



Ben$ gem install glib2 -v '2.1.0'
Building native extensions. This could take a while...
ERROR: Error installing glib2:
ERROR: Failed to build gem native extension.

/Users/Ben/.rvm/rubies/ruby-2.1.5/bin/ruby -r ./siteconf20150331-23534-17ib06g.rb extconf.rb
checking for -Wall option to compiler... yes
checking for -Waggregate-return option to compiler... yes
checking for -Wcast-align option to compiler... yes
checking for -Wextra option to compiler... yes
checking for -Wformat=2 option to compiler... yes
checking for -Winit-self option to compiler... yes
checking for -Wlarger-than-65500 option to compiler... yes
checking for -Wmissing-declarations option to compiler... yes
checking for -Wmissing-format-attribute option to compiler... yes
checking for -Wmissing-include-dirs option to compiler... yes
checking for -Wmissing-noreturn option to compiler... yes
checking for -Wmissing-prototypes option to compiler... yes
checking for -Wnested-externs option to compiler... yes
checking for -Wold-style-definition option to compiler... yes
checking for -Wpacked option to compiler... yes
checking for -Wp,-D_FORTIFY_SOURCE=2 option to compiler... yes
checking for -Wpointer-arith option to compiler... yes
checking for -Wswitch-default option to compiler... yes
checking for -Wswitch-enum option to compiler... yes
checking for -Wundef option to compiler... yes
checking for -Wunsafe-loop-optimizations option to compiler... yes
checking for -Wwrite-strings option to compiler... yes
checking for rb_define_alloc_func() in ruby.h... yes
checking for rb_block_proc() in ruby.h... yes
checking for new allocation framework... yes
checking for attribute assignment... no
checking for Win32 OS... no
checking for gobject-2.0 version (>= 2.12.0)... yes
checking for gthread-2.0... yes
checking for unistd.h... yes
checking for io.h... no
checking for g_spawn_close_pid() in glib.h... yes
checking for g_thread_init() in glib.h... yes
checking for g_main_depth() in glib.h... yes
checking for g_listenv() in glib.h... yes
checking for rb_check_array_type() in ruby.h... yes
checking for rb_check_hash_type() in ruby.h... yes
checking for rb_exec_recursive() in ruby.h... yes
checking for rb_errinfo() in ruby.h... yes
checking for rb_sourcefile() in ruby.h... yes
checking for rb_sourceline() in ruby.h... yes
checking for ruby_set_current_source() in ruby.h... no
checking for rb_thread_blocking_region() in ruby.h... yes
checking for ruby_native_thread_p() in ruby.h... yes
checking for rb_thread_call_with_gvl() in ruby.h... yes
checking for rb_str_new_cstr() in ruby.h... yes
checking for rb_gc_register_mark_object() in ruby.h... yes
checking for rb_exc_new_str() in ruby.h... yes
checking for curr_thread in ruby.h,node.h... no
checking for rb_curr_thread in ruby.h,node.h... no
creating ruby-glib2.pc
creating glib-enum-types.c
creating glib-enum-types.h
creating Makefile

make "DESTDIR=" clean

make "DESTDIR="
compiling glib-enum-types.c
warning: unknown warning option '-Wunsafe-loop-optimizations'; did you mean '-Wunavailable-declarations'? [-Wunknown-warning-option]
glib-enum-types.c:1181:9: error: use of undeclared identifier 'G_WIN32_OS_ANY'
{ G_WIN32_OS_ANY, "G_WIN32_OS_ANY", "any" },
^
glib-enum-types.c:1182:9: error: use of undeclared identifier 'G_WIN32_OS_WORKSTATION'
{ G_WIN32_OS_WORKSTATION, "G_WIN32_OS_WORKSTATION", "workstation" },
^
glib-enum-types.c:1183:9: error: use of undeclared identifier 'G_WIN32_OS_SERVER'
{ G_WIN32_OS_SERVER, "G_WIN32_OS_SERVER", "server" },
^
1 warning and 3 errors generated.
make: *** [glib-enum-types.o] Error 1

make failed, exit code 2

Error installing nokogiri gem with rbenv ruby 2.2.1

I'm trying to install a fresh nokogiri gem on a rails app like so:



gem install nokogiri -v '1.4.4'


I'm getting this error:



Building native extensions. This could take a while...
ERROR: Error installing nokogiri:
ERROR: Failed to build gem native extension.

/Users/development/.rbenv/versions/2.2.1/bin/ruby -r ./siteconf20150331-4057-14pcvq9.rb extconf.rb
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers. Check the mkmf.log file for more details. You may
need configuration options.

Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/Users/development/.rbenv/versions/2.2.1/bin/$(RUBY_BASE_NAME)
extconf.rb:10:in `<main>': uninitialized constant Config (NameError)

extconf failed, exit code 1

Gem files will remain installed in /Users/development/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/nokogiri-1.4.4 for inspection.
Results logged to /Users/development/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/extensions/x86_64-darwin-14/2.2.0-static/nokogiri-1.4.4/gem_make.out


I'm using rebenv ruby 2.1.1, so this is in a gemset.


Also this might help, this is my brew list:



autoconf freexl gpp libpng lzlib postgis redis
automake gdal imagemagick libspatialite makedepend postgresql ruby-build
boost geoip jpeg libtiff mpfr proj s3cmd
cgal geos json-c libtool openssl qt sfcgal
cmake giflib libgeotiff libxml2 phantomjs rbenv sqlite
freetype gmp liblwgeom libxslt pkg-config readline xz


Thanks for your help, I could really do with this working, there's a lot of similar fixes online however none of them have fixed my issue.


deny specific number(0) on rails 3 numeric validation

I can't figure out how to deny only 0 from my validation. jQuery is not an option and :other_to doesn't exist in rails 3.0


Ruby on Rails User can only edit a preference, not see list or create new

I am adding in user preferences in my Ruby on Rails application, and what I am trying to currently do is make it so that a user can only edit their preferences, so not create a new one or view a list of everybody's preferences. This requires a new preference to be made when a new user is made with the id from the users table appearing in the user_id column in the preferences table.


This is the schema:



create_table "perferences", force: :cascade do |t|
t.integer "user_id"
t.integer "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "colour"
end

create_table "users", force: :cascade do |t|
t.string "password_digest"
t.string "role"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "first_name"
t.string "last_name"
t.string "house_no"
t.string "street"
t.string "town"
t.string "postcode"
t.string "email"
t.date "date_of_birth"
end


Users_controller:



def create
@user = User.new(user_params)
if @user.save
# login is achieved by saving a user's 'id' in a session variable,
# accessible to all pages
session[:user_id] = @user.id
UserMailer.welcome_email(@user).deliver_now
redirect_to films_path
else
render action: "new"
end
end


And my routes.rb:



resources :perferences
resources :prices
# get 'perferences/index', post: 'perferences#new'
# post 'perferences/index', to: 'perferences#new'
# match 'perferences' => 'perferences#create', :via => [:post]

post 'reviews/new/:id', to: 'reviews#new'
get 'reviews/new/:id', to: 'reviews#new'
#resources :showings

get 'sessions/new'
get 'sessions/create'
get 'sessions/destroy'
controller :sessions do
get 'login' => :new
post 'login' => :create
get 'logout' => :destroy
end

#post 'films/search', to: 'films#search'
get 'films/index'
get 'categories/index'
get 'certificates/index'

root 'films#index'

post 'films/search', to: 'films#search'
post 'films/search_1', to: 'films#search_1'
post 'films/search_2', to: 'films#search_2'
post 'films/search_3', to: 'films#search_3'
post 'films/search_4', to: 'films#search_4'
post 'films/search_5', to: 'films#search_5'
post 'films/search_6', to: 'films#search_6'

post 'films/display_products_by_genre', :to => 'films#display_products_by_genre'
get 'films/display_products_by_genre', :to => 'films#display_products_by_genre'

post 'seats/display_seats_by_screen', :to => 'seats#display_seats_by_screen'
get 'seats/display_seats_by_screen', :to => 'seats#display_seats_by_screen'

post 'screens/display_screens_by_showing', :to => 'screens#display_screens_by_showing'
get 'screens/display_screens_by_showing', :to => 'screens#display_screens_by_showing'

post 'films/multi_find', :to => 'films#multi_find'
get 'films/multi_find', :to => 'films#multi_find'

post 'seats/multi_find', :to => 'seats#multi_find'
get 'seats/multi_find', :to => 'seats#multi_find'
post 'screens/multi_find', :to => 'screens#multi_find'
get 'screens/multi_find', :to => 'screens#multi_find'

resources :users
resources :films
resources :categories
resources :certificates
resources :showings
resources :bookings
resources :seats
resources :screens
resources :reviews
resources :films do
resources :showings
end
resources :showings do
resources :seats
end


match '*a', to: 'errors#routing', via: [:get, :post]


Note the commented out lines in the routes are what I have tried to get it so that rather than going to the perferences/index page, the user is sent to perferences/edit page where they edit their own perferences.


To clarify what I need to do:



  • Make it so that a user cannot go to the perferences/index or perferences/new page but are sent to the perferences/edit page where they edit their existing preferences

  • Create a new preference when a new user is created so that they have a preference to edit, even if it has nothing but their user_id so far


Can someone please help.


ActionMailer Attachment omitting body gzip

I have a script that generates a sql dump. I am trying to automate this further so it sends out an email with gzipped attachment. All works apart from when I receive the email it returns the following:



-- Content-Type: application/x-gzip; charset=UTF-8 Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename=company_dump.gz Content-ID: <551979ffcf8d6_239f11b2ff074555@home-System-Product-Name.mail> H4sICN1PGVUAAy4uL2NvbXBhbnlfZXh0cmFjdF9kdW1wLnNxbADsvft22zi2 8Pn31FPgq/nDqfPFadwvOtOz2rfEqThOynba3WdqlouSKJsdiXRTUlzus3qt 7zW+15snGYAXCSQhiTJ1cTmqqk7HMEmAxP7tvQFsbOzvg4+Pl7+cge54cA8Q fIMIAMfBcBQHbcDesDdEvga9KAZdvx144X4/CMe/79+GY/Dqd8lvOP3ph/19 /R84jYajFuhHHa9/p/8K9D/H3shre0O/BcZfb9rt8a25bv9J/5g7L/34mx8D /b9hEIX/R9q4fThuj8PRWDccv4H0Dfrhhz/9x/+gEEEELk+uwF8+nR3fHJ0e XBwcXZ1c3Oiim6Oz9yfnV3/+y19cxeA//vSfC59wcXL55ezqsvKIrHzWMz6d nR1cvf90rv92fn5yZP5qHuEorj7h/ODjySUYj3rS/h2ZPv3q/ceTm//6dH6i Hzn5e/Xa6WV7/xPCFoR702sgotPnfTl//8uXE/3iJ0cfzJsWfn4Nir+GMx7y 9tPFyft35zcfTv4+fVK18DVwXAhnfEYtrDcfPx2b98z/+hpMCvfOP90cfLn6 dPPXgzPdPv1V/+vk4pP1kgiVnnX+6erkMntY8vf0aWlx2ohMxK+8dt8HGo1x ZzSO/QSLUVL2m9f17kfBN//m3nsc+OHoRmPQb3udr8PfzM0/HF98+gyuDg7P TsD7t+Dkb+8vtZjMu6v85kPvm9+96QxvOv1AX2nwAn8Gf/lL586Lvc7Ij2+G /ij/ZeXDOa/681Scji5ODq5OsgbOaxZ49QMAvwXd30AQjl4h9BPQ3wmcfzk7



My supported code is below:



class Notifier < ActionMailer::Base

def company_extract_email(file)
recipients = 'Internal <internal@some_domain.com>'
from = 'noreply@some_domain.com'
subject = 'See attached'
message = mail(:to => recipients, :from => from, :subject => subject, :reply_to => reply_to) do |format|
format.html { render :text => 'See the attached'}
end
attachments['company_dump.gz'] = {mime_type: 'application/x-gzip', content: File.read("#{file}.gz")}
reply_to = 'noreply@some_domain.com'
end
end


The following is called from within a script I've written:



def export_mysql(company, company_name)
extend ActionView::Helpers

conf = ActiveRecord::Base.connection_config
filename = "company_extract_dump"
file = "../#{filename}"

system("mysqldump -P 3306 -h #{conf[:host]} -u #{conf[:username]} -p #{conf[:database]} > #{file}.sql")

Zlib::GzipWriter.open("#{file}.gz") do |gz|
gz.orig_name = "#{file}.sql"
gz.write IO.binread("#{file}.sql")
end

size = number_to_human_size(File.size("#{file}.gz"), precision: 2)

if size < number_to_human_size(2.6e+7, precision: 2)
email = Notifier.company_extract_email(file)
email.deliver if email
end

File.delete("#{file}.sql")
File.delete("#{file}.gz")
end


I also did come across: ActionMailer 2.3.5 mangles my zip attachment. I have tried setting the content_transfer_encoding: "base64" but this does not make a difference.


Failed to load libmysql.dll file using Ruby on Rails 3

I am making one application using RoR with mysql.I followed the below steps for making app with mysql.


1-rails new projectname -d mysql


2-rails generate scaffold Post title:string body:text


After running the 2nd step I got the following error.


Error:



Failed to load libmysql.dll from C:\Ruby193\lib\ruby\gems\1.9.1\gems\mysql2-0.3.
18-x86-mingw32\vendor\libmysql.dll


I have installed mysql in my system and copied the libmysql.dll file from mysql-connector-c-noinstall-6.0.2-win32\lib\libmysql.dll to C:\Ruby193\bin still i am getting the above error.Please try to help me to resolve this error and i am also interested to know if my mysql DB is present in some other instance instead of my local system how can i connect it using Rails.


I am using Rails version-3.2.19 and win-xp in my system.


Ruby on Rails change background colour in CSS according to database

In my Ruby on Rails application I am trying to allow the user to choose their colour and have this as the sites background.


In my schema I have this preferences table:



create_table "perferences", force: :cascade do |t|
t.integer "user_id"
t.integer "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "colour"
end


The CSS background colour is in the following line:



body{line-height:1;height:100%;width:100%;color:#B2BFCB;background:#002952;text-align:center;font-family:"Apercu Regular", Calibri, sans-serif;font-weight:normal;font-style:normal;margin:0;padding:0;}


But I am unsure as to how to update the colour based upon the colour in the database.


I have tried to follow this link: http://ift.tt/19vMCMZ But I got the error: undefined method formatted_colour_path for #<#<Class:0x6daa0a8>:0x6881b98>


In the view:


In the perferences controller:



def show
@colour = Perference.find_by(user_id: session[:user_id]).colour
respond_to do |format|
format.html
format.css
end
end


Can someone please help. I understand that I need to retrieve the colour from the database and then use this to update the CSS, but I am not sure how to do this.


Get name of the day

how can I get the name of the day in Ruby.


For eg. something like that:



a = Date.today
a.day_name
=> Tuesday


the only thing i could find was .wday but that only returns for the number of the day in the week



a.wday
=> 2

How to process array of hashes in a better way

Below is the array of hashes from the PGResult set.



result = [
{"type" => 1 , "original" => "true", "count" => "10"},
{"type" => 1 , "original" => "false", "count" => "20"},
{"type" => 2 , "original" => "false", "count" => "30"},
{"type" => 2 , "original" => "true", "count" => "40"},
{"type" => 3 , "original" => "true", "count" => "50"},
{"type" => 3 , "original" => "false", "count" => "60"}
]


I want to process the above array of hashes to the below format. total_count = count of original("true") - count of original("false") for each type!



result = [
{
"type" => 1, "total_count" => "10",
"type" => 2, "total_count" => "10",
"type" => 3, "total_count" => "-10",
}

]


any hint to process the above array ?


A form is there inside joinus method of , how to submit the form values on rails?what should I do?

I have controller Pages which have methods like home , aboutus , joinus ,contactus and mad.


joinus also has a form given below.


JOIN US


Name


Email


Address


Number


SUBMIT


when I click on submit, Routing error is coming


No route matches [POST] "/pages/joinus"


Rails.root: C:/NEW/charityapp


Application Trace | Framework Trace | Full Trace Routes


Routes match in priority from top to bottom


Helper HTTP Verb Path Controller#Action Path / Url

pages_home_path GET /pages/home(.:format) pages#home root_path GET / pages#home pages_aboutus_path GET /pages/aboutus(.:format) pages#aboutus pages_joinus_path GET /pages/joinus(.:format) pages#joinus pages_contactus_path GET /pages/contactus(.:format) pages#contactus pages_mad_path GET /pages/mad(.:format) pages#mad


How to use HTML5 inputs in Rails 3.2.12

is it possible to use HTML5 input type date for a Ruby and Rails 3.2.12 form?


When its possible how can I use it?


Thanks


How do I integrate BigBlueButton into my rails application?

I couldn't find any proper documentation of it anywhere, so it would be helpful if some of your writers can post a topic about this integration of BigBlueButton.


Deleted action dispatch by mistake, how to get it back correctly so that i can load my local host server properly?


C:\NEW\`charityapp`>rails s
=> Booting WEBrick
=> Rails 4.1.8 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0
.1 (--binding option)
=> Ctrl-C to shutdown server
Exiting
C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/lib/rails/engi
ne.rb:527:in `routes': cannot load such file -- action_dispatch/routing/route_set
(LoadError)
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/engine.rb:574:in `block in <class:Engine>'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/initializable.rb:30:in `instance_exec'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/initializable.rb:30:in `run'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/initializable.rb:55:in `block in run_initializers'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:150:in `block in
tsort_each'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:183:in `block (2
levels) in each_strongly_connected_component'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:210:in `block (2
levels) in each_strongly_connected_component_from'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:210:in `block (2
levels) in each_strongly_connected_component_from'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:210:in `block (2
levels) in each_strongly_connected_component_from'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:210:in `block (2
levels) in each_strongly_connected_component_from'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:219:in `each_stro
ngly_connected_component_from'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:209:in `block in
each_strongly_connected_component_from'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/initializable.rb:44:in `each'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/initializable.rb:44:in `tsort_each_child'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:203:in `each_stro
ngly_connected_component_from'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:209:in `block in
each_strongly_connected_component_from'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/initializable.rb:44:in `each'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/initializable.rb:44:in `tsort_each_child'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:203:in `each_stro
ngly_connected_component_from'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:209:in `block in
each_strongly_connected_component_from'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/initializable.rb:44:in `each'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/initializable.rb:44:in `tsort_each_child'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:203:in `each_stro
ngly_connected_component_from'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:209:in `block in
each_strongly_connected_component_from'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/initializable.rb:44:in `each'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/initializable.rb:44:in `tsort_each_child'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:203:in `each_stro
ngly_connected_component_from'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:182:in `block in
each_strongly_connected_component'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:180:in `each'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:180:in `each_stro
ngly_connected_component'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/tsort.rb:148:in `tsort_eac
h'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/initializable.rb:54:in `run_initializers'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/application.rb:300:in `initialize!'
from C:/NEW/charityapp/config/environment.rb:5:in `<top (required)>'
from C:/NEW/charityapp/config.ru:3:in `require'
from C:/NEW/charityapp/config.ru:3:in `block in <main>'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/r
ack/builder.rb:55:in `instance_eval'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/r
ack/builder.rb:55:in `initialize'
from C:/NEW/charityapp/config.ru:in `new'
from C:/NEW/charityapp/config.ru:in `<main>'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/r
ack/builder.rb:49:in `eval'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/r
ack/builder.rb:49:in `new_from_string'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/r
ack/builder.rb:40:in `parse_file'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/r
ack/server.rb:277:in `build_app_and_options_from_config'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/r
ack/server.rb:199:in `app'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/commands/server.rb:50:in `app'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/r
ack/server.rb:314:in `wrapped_app'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/commands/server.rb:130:in `log_to_stdout'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/commands/server.rb:67:in `start'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/commands/commands_tasks.rb:81:in `block in server'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/commands/commands_tasks.rb:76:in `tap'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/commands/commands_tasks.rb:76:in `server'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/commands/commands_tasks.rb:40:in `run_command!'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.1.8/l
ib/rails/commands.rb:17:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'

lundi 30 mars 2015

How can I view the total number of registered users on my log file (webapp is ROR using Devise)?

I built a webapp using Ruby on Rails and devise for user authentication and setup.


I just want to be able to do two things: 1) see the list of registered users (emails) that have signed up and 2) count the number of registered users.


How can I extract this information from my log files using my terminal?


Thanks!


New password could not set into DB using Ruby on Rails 3

I am trying to reset the new password using Rails 3.When i insert new password(i.e.123456789) and clicked on submit button it gave me the following error.


Error:



NoMethodError in HomesController#resubmitpass

undefined method `stringify_keys' for "123456789":String
Rails.root: C:/Site/library_management1

Application Trace | Framework Trace | Full Trace
app/controllers/homes_controller.rb:179:in `resubmitpass'


Please check my below codes and let me to know how it will be solved ?


views/homes/resetpass.html.erb



<center>
<%= form_for :users,:url => {:action =>'resubmitpass',:id =>params[:id] } do |f| %>
<div class="pass-div">
<p>
<%= f.password_field :password,:id => "pre-pass",placeholder:"Enter your new password" %>
</p>
<p>
<%= f.password_field :password_confirmation ,:id => "pre-pass", placeholder:"Enter your password again" %>
</p>
<p>
<%= f.submit 'Update',:class => "btn btn-success" %>
</p>
</div>
<% end %>
</center>


controller/homes_controller.rb



class HomesController < ApplicationController
before_filter :authenticate_admin!,only: [:admin]
def index

end
def admin

end
def managebooks
@books=Book.new
if params[:id]
@books=Book.find(params[:id])
@book=Book.all
end
end
def savebooks
@books=Book.new(params[:books])
if @books.save
flash[:notice]="Data has submitted successfully"
flash[:color]="valid"
redirect_to :action => 'managebooks',:id => @books.id
else
flash[:notice]="Data couldnot submitted successfully"
flash[:color]="invalid"
render 'managebooks'
end
end
def remove
@books=Book.find(params[:id])
@books.destroy
end
def books

end
def showbooks
@books=Book.all
end
def searchbooks
@books=Book.all
end
def member
@users=User.new
end
def registration
@users=User.new
end
def savedata
@users=User.new(params[:users])
if @users.save
flash[:notice]="Data has submitted successfully"
flash[:color]="valid"
redirect_to :action => 'member'
else
flash[:notice]="Data could not submitted successfully"
flash[:color]="invalid"
render 'registration'
end
end
def issuebooks
@issues=Issue.new
end
def savedissuebooks
@issues=Issue.new(params[:issues])
if @issues.save
flash[:notice]="information has saved successfully"
flash[:color]="valid"
redirect_to :action => 'member'
else
flash[:notice]="Data couldnot saved"
flash[:color]="invalid"
render 'issuebooks'
end
end
def availablebooks

@books=Book.all
end
def userissues
@issues=Issue.all
end
def magazine
@magazines=Magazine.new
end
def savemagazines
@users=User.find(params[:id])
@magazines=Magazine.new(params[:magazines])
@magazines.user_id=@users.id
if @magazines.save
flash[:notice]="Data submitted successfully"
flash[:color]="valid"
redirect_to :action => "member"
else
flash[:notice]="Data could not saved"
flash[:color]="invalid"
render 'magazines'
end
end
def magazineissue
@magazines=Magazine.all
@users=User.find @magazines.first.user_id
end
def blog
@blogs=Blog.new
end
def savecomments
@users=User.find(params[:id])
@blogs=Blog.new(params[:blogs])
@blogs.user_id=@users.id
if @blogs.save
flash[:notice]="Comment has been posted successfully"
flash[:color]="valid"
redirect_to :action => "showcomment"
else
flash[:notice]="Comment could not saved"
flash[:color]="invalid"
render 'blog'
end
end
def showcomment
@blogs=Blog.all
end
def newspaper
@newspapers=Newspaper.new
end
def savenewspaper
@users=User.find(params[:id])
@newspapers=Newspaper.new(params[:newspapers])
@newspapers.user_id=@users.id
if @newspapers.save
flash[:notice]="newspaper data saved successfully"
flash[:color]="valid"
redirect_to :action => "member"
else
flash[:alert]="Data could not saved successfully"
flash[:color]="invalid"
render 'newspaper'
end
end
def adminnewspaperissue
@newspapers=Newspaper.all
@users=User.find @newspapers.first.user_id
end
def userprofile
@users=User.find(params[:id])
end
def updatedata
@users=User.find(params[:id])
if @users.update_attributes(params[:users])
flash[:notice]="User Data has updated"
flash[:color]="valid"
redirect_to :action => 'member'
else
flash[:alert]="Data could not updated"
flash[:color]="invalid"
render 'userprofile'
end
end
def forgetpass
@users=User.new
end
def sendemail
@users=User.find_by_email(params[:users][:email])
if @users.email==params[:users][:email]
UserMailer.registration_confirmation(@users).deliver
flash[:notice]="check your mail to reset your password"
flash[:color]="valid"
redirect_to :action => "checkmail"
else
flash[:alert]="You might entered wrong email address"
flash[:color]="invalid"
render 'forgetpass'
end
end
def resetpass
@users=User.new
end
def resubmitpass
@users=User.find(params[:id])
if @users.update_attributes(params[:users][:password])
flash[:notice]="Your password updated succesfully"
flash[:color]="valid"
redirect_to :action => "member"
else
flash[:alert]="Your password could not updated successfully"
flash[:color]="invalid"
render 'resetpass'
end
end
end


model/user.rb



class User < ActiveRecord::Base
attr_accessible :address, :email, :first_name, :last_name, :password, :password_hash, :password_salt, :tel_no ,:password_confirmation
attr_accessor :password
before_save :encrypt_password
EMAIL_REGEX = /\A[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :first_name, :presence => true, :length => {:in => 3..10}
validates :last_name , :presence => true , :length => {:in => 3..10}
validates :tel_no , :presence => true , :length => {:in => 1..10}
validates :password, :confirmation => true
validates_length_of :password, :in => 6..20, :on => :create
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end

def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
has_many :issue
has_many :book
has_many :magazine
has_many :blog
has_many :newspaper
end


db/migrate/20150311112733_create_users.rb



class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :email
t.string :password
t.string :tel_no
t.string :address
t.string :password_hash
t.string :password_salt
t.timestamps
end
end
end


Actually the error is coming in this line "if @users.update_attributes(params[:users][:password])".Please help me to resolve this error.


Full URL is not coming when using action mailer in Rail 3?

I am trying to implement reset password feature in my app using Ruby on Rails.I am using action mailer to send link to user's email.The email is delivering to user with link but when user is clicking on that link the full URL is not coming(i.e-"localhost:3000/homes/resetpass").Only "/homes/resetpass" is coming.Please check my following codes and help me to resolve this issue.


views/user_mailer/registration_confirmation.html.erb



<p><%= @users.first_name %>,</p>

<p>Thank you for registering!</p>

<p>Edit Your Password <%= link_to "Click Here",homes_resetpass_path(:id => @users.id ),:host => "localhost:3000" %></p>


mailers/user_mailers.rb



class UserMailer < ActionMailer::Base
default from: "rajatpradhan474@gmail.com"
def registration_confirmation(user)
@users = user
mail(:to => user.email, :subject => "Registered")
end
end


config/initializers/setup_mail.rb



ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:user_name => "rajatpradhan474@gmail.com",
:password => "**********",
:authentication => "plain",
:enable_starttls_auto => true
}
ActionMailer::Base.default_url_options[:host] = "localhost:3000"

Controller method using JS doesn't return/render data when called within modal popup

I've been stuck with this problem a couple of days, and I didn't find anything that could help me.


The idea is to get price_scenarios index view rendered in a modal popup. For each price_scenario shown in the table, a controller method, "price" is called. This method gets some info from the model and render it formated using JSON. This way of getting the prices was coded for a previous developer who is no longer in the project, and is necessary becouse price values can take a while to be calculated, so a small wheel gif is rendered when page loads.


The problem: price_scenarios "price" method doesn't render any value. This only happens if "price" is called within the index view rendered in a modal popup, I've tried doing this rendering price_scenarios index and it works fine. Also, this method is succesfully used in many other views of the app. I think it must be a problem with format responses, due to call the method from a popup, but everything I've tried haven't improved the results.


product show.html.haml a button displaying price_scenarios index as a modal popup:



%h3
= model_class.human_attribute_name(:price)
= link_to PriceScenario.model_name.human(count: 2), formula_product_price_scenarios_path(@formula, @product), remote: true, data: {toggle: "modal", target: "#price_scenarios"}, class: "btn"

#price_scenarios(class="modal hide fade" role="dialog" aria-labelledby="Delta" aria-hidden="true")


price_scenarios_controller.rb definition of index and price methods



class PriceScenariosController < ApplicationController
before_filter :require_client
load_and_authorize_resource :formula
load_and_authorize_resource :product, :through => :formula
before_filter :get_tuple, only: :price

def index
@price_scenarios = @product.price_scenarios
respond_to :js
end

def price
@price_scenario = PriceScenario.find(params[:id])
@price = @price_scenario.shifted_price(@tuple)
@price_units = @product.price_units

respond_to do |format|
format.html { render partial: 'price'}
format.json { render json: {price: @price, units: @price_units}}
end
end


price_scenario index.js.haml view renders index view in the modal:



$("#price_scenarios").html("#{escape_javascript(render partial: 'modal_price_scenarios')}");


_modal_price_scenarios.html.haml view rendered in the modal, "price" is called within it.



#modal_price_scenarios(class="modal" role="dialog" aria-labelledby="Delta" aria-hidden="true")

- model_class = PriceScenario

.modal-body
%table.table.table-striped
%thead
%tr
%th= model_class.model_name.human
%th= model_class.human_attribute_name(:price)
%th= model_class.human_attribute_name(:references)
%tbody
- @price_scenarios.each do |scenario|
%tr
%td= scenario.name
%td.price{:"data-product-price" => price_formula_product_price_scenario_path(@formula, @product, scenario)}
= image_tag('ajax-loader.gif')


-Price.html.haml partial rendered by price_scenarios price method.



= "#{@price} #{@price_units}"


product_price.js



$(function(){
$('[data-product-price]').each(function(){
var url = $(this).data('product-price')
$.ajax({
url: url,
cache: false,
dataType: "json"
}).done(function( data ) {
var priceWithUnits = data['price'] + ' ' + data['units']
$('[data-product-price="' + url + '"]').html(priceWithUnits);
});
});
});

dimanche 29 mars 2015

Email could not sent using Ruby on Rails 3?

I am trying to send one email through action mailer using ROR. But it can not sent even if it is not showing any error.I am explaining my codes below .Please check these and let me to know where i did mistake and what might be the possibility solutions.


views/users/_form.html.erb:



<%= form_for(@user) do |f| %>
<% if @user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>

<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>

<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>


views/user_mailer/registration_confirmation.html.erb:



Thank you for registering!


controller/users_controller.rb



class UsersController < ApplicationController
# GET /users
# GET /users.json
def index
@users = User.all

respond_to do |format|
format.html # index.html.erb
format.json { render json: @users }
end
end

# GET /users/1
# GET /users/1.json
def show
@user = User.find(params[:id])

respond_to do |format|
format.html # show.html.erb
format.json { render json: @user }
end
end

# GET /users/new
# GET /users/new.json
def new
@user = User.new

respond_to do |format|
format.html # new.html.erb
format.json { render json: @user }
end
end

# GET /users/1/edit
def edit
@user = User.find(params[:id])
end

# POST /users
# POST /users.json
def create
@user = User.new(params[:user])

respond_to do |format|
if @user.save
UserMailer.registration_confirmation(@user).deliver
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render json: @user, status: :created, location: @user }
else
format.html { render action: "new" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end

# PUT /users/1
# PUT /users/1.json
def update
@user = User.find(params[:id])

respond_to do |format|
if @user.update_attributes(params[:user])
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end

# DELETE /users/1
# DELETE /users/1.json
def destroy
@user = User.find(params[:id])
@user.destroy

respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
end
end
end


mailers/user_mailer.rb



class UserMailer < ActionMailer::Base
default from: "subhrajyotipradhan@gmail.com"
def registration_confirmation(user)
mail(:to => user.email, :subject => "Registered")
end
end


config/initializers/setup_mail.rb



ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:user_name => "subhrajyotipradhan@gmail.com",
:password => "w5rtcoditek123",
:authentication => "plain",
:enable_starttls_auto => true
}

Error setting up Rails -- Could not find gem "actionview"

I'm not sure why I'm running into this problem as i had previously set up Rails on my Mac successfully. However, I had to set it up again and ran into this error:



ERROR: Could not find a valid gem 'actionview' (= 4.2.1) in any repository
ERROR: Possible alternatives: actionview


I tried installing the actionview gem:



gem install actionview


Installation was successful, but I''m still getting the error messages above after running



sudo gem install rails

Whether to MD5 on server side or on client side?

I'm building a Ruby on Rails page where there is a list of users, and I'd like to assign a random color to each user based on his email address so that the random color is the same for that user across sessions but different between users.


I've decided that I could digest the email in MD5 and take the first 6 characters. This should give me the same hex for the same email every time, and the hex will be different for different emails.


Now, I'm trying to decide whether I want to do this on the server side (in Ruby) or on the client side (in JavaScript). On the one hand, I already have a lot of JavaScript running on the page so I don't want the page to look too slow, but on the other, I don't want to bog down the server every time this page is loaded. In the rails console, calculating the MD5 of a string isn't super duper fast. It took a second to return something. I guess my questions are:



  1. Generally, how computationally expensive is creating an MD5 of a string?

  2. Is there a significant reason to do the digest in the client-side code vs the server-side?


It might sound like I'm over-optimizing here, which is probably true, but I'm also just curious whether there is a rule that I should follow when making decisions like these.


Thanks in advance


Solr Sunspot Autocomplete Text Field Not Working

I am using the sunspot_autocomplete gem to implement auto suggest to my search bar. Just need some help creating the text field. I am using rails 3.


Before I installed the gem, my search bar's code looked like this:



<%= form_tag dairies_path, :method => :get do %>
<p>
<%= text_field_tag :search, params[:search], style:"width:550px; height:30px;", :autofocus => true %><br>
<%= submit_tag "Search!", :name => nil, class: "btn btn-primary btn-lg", style: "margin-top:20px" %>
</p>
<% end %>


The autocomplete gem requires this code for a text field:



<%= autosuggest_text_field "dairy", "title", "http://ift.tt/1jPxatM", "dairy_title"%>


My question is do I replace all of the search bar code with that ^ or do I just replace the text_field_tag line? I have either been getting errors, or the entire code shows up on my website. Sorry for the beginner question. Still lots to learn! Thank you for your help.


Create automatically methods

Lets say I have this House class:



class House

def self.building_steps
[
[Worker, :buy_material],
[Worker, :blend_material],
[Truck, :remove_ground],
......
#more Tasks defined by [CLASS,METHOD]
]
end

def self.buy_material
check_process(Worker, __method__)
end

def self.blend_material
check_process(Worker, __method__)
end

def self.remove_ground
check_process(Truck, __method__)
end
............
#More Methods that have same Method names like the building steps

end


As you can see in my code I have a lot of repetitions.


My question is how i can automatically define the class methods from the building_steps list.


So that I dont have to add the methods manually!


I search something like:



House.building_steps.each do |step|
define_house_method_with_name( step[1] )
in this method do
check_process(step[0], step[1])
end
end


Is something like this possible? Thanks!


Rails 4 OmniAuth-Facebook request.env return nil

I have an application that uses Rails 4, OmniAuth and OmniAuth-facebook and in the controller action "request.env['omniauth.auth']" is nil.


GemFile



gem 'omniauth'
gem 'omniauth-facebook' # Facebook authentication
gem 'omniauth-twitter' #twitter authentication
gem "koala", "~> 1.10.0rc" # Facebook API
...


config/initializers/omniauth.rb



Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, FACEBOOK_CONFIG['app_id'].to_s, FACEBOOK_CONFIG['secret'].to_s, {:scope => 'xmpp_login'}
provider :twitter, '8v3vAAc0k878b#######'
end


Controller:



class SomeController
def index
raise env["omniauth.auth"].inspect
end
...


The result is simply: 'nil'


What is missing?


samedi 28 mars 2015

using Cancan to get company_a not to see company_b

I have created MVC for Product and there three companies that can enter data for their products. each companies have their own users who can enter product information. I want to use Cancan in a way that the company_a and company_b cannot see each other products listing nor can be able to delete or edit; however, I want company_c be able to see all product listing. Admin should be able to see all and edit/delete all.


Not included assets in rails app

My application.js (in app/assets/) looks like:



//= require jquery
//= require jquery_ujs
//= require_tree .


the problem is that generated HTML contains only (not the tree):



<script src="/assets/application.js?body=1" type="text/javascript"></script>


what I expected is e.g. jquery.js, etc.


This problem occurs only on my Mac OS X development machine. (tested also on OpenSuse - unix machine and everything works).


What I have tried:



  1. replace Gemfile.lock (now identical with unix machine except json ~> 1.8.2 instead of 1.8.0) and reinstall all gems:



gem uninstall --all
bundle install


  1. change ruby version (tested 1.9, 2.1, 2.2)

  2. googling around what is wrong with sprockets (without any success)

  3. elaborating with rake assets:precompile --track



** Invoke assets:precompile:all (first_time)
** Execute assets:precompile:all
** Invoke assets:precompile:primary (first_time)
** Invoke assets:environment (first_time)
** Execute assets:environment
** Invoke environment (first_time)
** Execute environment
** Invoke tmp:cache:clear (first_time)
** Execute tmp:cache:clear
** Execute assets:precompile:primary
Compiled application.js (1ms) (pid 20541)
Compiled application.css (0ms) (pid 20541)

Ruby version 2.2, rails version 3.1.12. I could include Gemfile if necessary but bundle install works without any problem.


Installing Rails on Mac OS Yosemite v10.10.2 (FNG)

I'm trying to install Rails onto my Mac and keep running into a this issue. I have no coding/programming experience and am trying to get set up so I can start learning.


I have gone through everything on install rails.com and am not sure what to do.


Your help is appreciated.


make install failed, exit code 2


Gem files will remain installed in /Users/feferrada/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.6.2 for inspection. Results logged to /Users/feferrada/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/extensions/x86_64-darwin-14/2.2.0-static/nokogiri-1.6.6.2/gem_make.out


output integer as phone number format in view

I am trying to show show this as a formatted phone number like: xxx-xxx-xxxx instead of just a number string like it currently is ..any help would be great!



<% if @post.phone.present? %>
<h4>Phone: <small> <%= @post.phone %><br></h4>
<% end %>

yosemite can't install simple_oauth gem

I upgraded to yosemite recently. I have an existing Rails 3 (ruby 1.9.3) app. When I try to run "bundle install" I keep bumping to this issue:



Installing simple_oauth 0.3.1

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

/usr/local/rvm/rubies/ruby-1.9.3-p551/bin/ruby -r ./siteconf20150328-85112-1qe3ej8.rb extconf.rb
checking for main() in -lobjc... yes
creating Makefile

make clean

make
compiling rr.cpp
clang: warning: argument unused during compilation: '-rdynamic'
rr.cpp:48:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
rr.cpp:151:44: warning: implicit conversion loses integer precision: 'long' to 'int' [-Wshorten-64-to-32]
return String::New(RSTRING_PTR(value), RSTRING_LEN(value));
~~~~~~ ^~~~~~~~~~~~~~~~~~
/usr/local/rvm/rubies/ruby-1.9.3-p551/include/ruby-1.9.1/ruby/ruby.h:674:6: note: expanded from macro 'RSTRING_LEN'
RSTRING_EMBED_LEN(str) : \
^~~~~~~~~~~~~~~~~~~~~~
/usr/local/rvm/rubies/ruby-1.9.3-p551/include/ruby-1.9.1/ruby/ruby.h:670:6: note: expanded from macro 'RSTRING_EMBED_LEN'
(long)((RBASIC(str)->flags >> RSTRING_EMBED_LEN_SHIFT) & \
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
rr.cpp:151:44: warning: implicit conversion loses integer precision: 'long' to 'int' [-Wshorten-64-to-32]
return String::New(RSTRING_PTR(value), RSTRING_LEN(value));
~~~~~~ ^~~~~~~~~~~~~~~~~~
/usr/local/rvm/rubies/ruby-1.9.3-p551/include/ruby-1.9.1/ruby/ruby.h:675:28: note: expanded from macro 'RSTRING_LEN'
RSTRING(str)->as.heap.len)
~~~~~~~~~~~~~~~~~~~~~~^~~
3 warnings generated.
compiling v8.cpp
clang: warning: argument unused during compilation: '-rdynamic'
compiling v8_array.cpp
clang: warning: argument unused during compilation: '-rdynamic'
compiling v8_callbacks.cpp
clang: warning: argument unused during compilation: '-rdynamic'
compiling v8_context.cpp
clang: warning: argument unused during compilation: '-rdynamic'
compiling v8_date.cpp
clang: warning: argument unused during compilation: '-rdynamic'
compiling v8_debug.cpp
clang: warning: argument unused during compilation: '-rdynamic'
compiling v8_exception.cpp
clang: warning: argument unused during compilation: '-rdynamic'
v8_exception.cpp:10:16: warning: unused variable 'stack' [-Wunused-variable]
static void* stack[20];
^
1 warning generated.
compiling v8_external.cpp
clang: warning: argument unused during compilation: '-rdynamic'
v8_external.cpp:10:9: warning: unused variable 'references' [-Wunused-variable]
VALUE references;
^
1 warning generated.
compiling v8_function.cpp
clang: warning: argument unused during compilation: '-rdynamic'
compiling v8_handle.cpp
clang: warning: argument unused during compilation: '-rdynamic'
compiling v8_locker.cpp
clang: warning: argument unused during compilation: '-rdynamic'
v8_locker.cpp:45:5: warning: control reaches end of non-void function [-Wreturn-type]
}
^
v8_locker.cpp:85:5: warning: control reaches end of non-void function [-Wreturn-type]
}
^
2 warnings generated.
compiling v8_message.cpp
clang: warning: argument unused during compilation: '-rdynamic'
compiling v8_object.cpp
clang: warning: argument unused during compilation: '-rdynamic'
v8_object.cpp:77:19: warning: unused variable 'proto' [-Wunused-variable]
Handle<Value> proto(rr_rb2v8(prototype));
^
1 warning generated.
compiling v8_script.cpp
clang: warning: argument unused during compilation: '-rdynamic'
compiling v8_string.cpp
clang: warning: argument unused during compilation: '-rdynamic'
v8_string.cpp:18:73: warning: implicit conversion loses integer precision: 'long' to 'int' [-Wshorten-64-to-32]
return rr_v8_handle_new(string_class, String::New(RSTRING_PTR(str), RSTRING_LEN(str)));
~~~~~~ ^~~~~~~~~~~~~~~~
/usr/local/rvm/rubies/ruby-1.9.3-p551/include/ruby-1.9.1/ruby/ruby.h:674:6: note: expanded from macro 'RSTRING_LEN'
RSTRING_EMBED_LEN(str) : \
^~~~~~~~~~~~~~~~~~~~~~
/usr/local/rvm/rubies/ruby-1.9.3-p551/include/ruby-1.9.1/ruby/ruby.h:670:6: note: expanded from macro 'RSTRING_EMBED_LEN'
(long)((RBASIC(str)->flags >> RSTRING_EMBED_LEN_SHIFT) & \
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
v8_string.cpp:18:73: warning: implicit conversion loses integer precision: 'long' to 'int' [-Wshorten-64-to-32]
return rr_v8_handle_new(string_class, String::New(RSTRING_PTR(str), RSTRING_LEN(str)));
~~~~~~ ^~~~~~~~~~~~~~~~
/usr/local/rvm/rubies/ruby-1.9.3-p551/include/ruby-1.9.1/ruby/ruby.h:675:28: note: expanded from macro 'RSTRING_LEN'
RSTRING(str)->as.heap.len)
~~~~~~~~~~~~~~~~~~~~~~^~~
v8_string.cpp:23:79: warning: implicit conversion loses integer precision: 'long' to 'int' [-Wshorten-64-to-32]
return rr_v8_handle_new(string_class, String::NewSymbol(RSTRING_PTR(str), RSTRING_LEN(str)));
~~~~~~ ^~~~~~~~~~~~~~~~
/usr/local/rvm/rubies/ruby-1.9.3-p551/include/ruby-1.9.1/ruby/ruby.h:674:6: note: expanded from macro 'RSTRING_LEN'
RSTRING_EMBED_LEN(str) : \
^~~~~~~~~~~~~~~~~~~~~~
/usr/local/rvm/rubies/ruby-1.9.3-p551/include/ruby-1.9.1/ruby/ruby.h:670:6: note: expanded from macro 'RSTRING_EMBED_LEN'
(long)((RBASIC(str)->flags >> RSTRING_EMBED_LEN_SHIFT) & \
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
v8_string.cpp:23:79: warning: implicit conversion loses integer precision: 'long' to 'int' [-Wshorten-64-to-32]
return rr_v8_handle_new(string_class, String::NewSymbol(RSTRING_PTR(str), RSTRING_LEN(str)));
~~~~~~ ^~~~~~~~~~~~~~~~
/usr/local/rvm/rubies/ruby-1.9.3-p551/include/ruby-1.9.1/ruby/ruby.h:675:28: note: expanded from macro 'RSTRING_LEN'
RSTRING(str)->as.heap.len)
~~~~~~~~~~~~~~~~~~~~~~^~~
4 warnings generated.
compiling v8_template.cpp
clang: warning: argument unused during compilation: '-rdynamic'
compiling v8_try_catch.cpp
clang: warning: argument unused during compilation: '-rdynamic'
compiling v8_v8.cpp
clang: warning: argument unused during compilation: '-rdynamic'
v8_v8.cpp:22:49: warning: implicit conversion loses integer precision: 'long' to 'int' [-Wshorten-64-to-32]
V8::SetFlagsFromString(RSTRING_PTR(string), RSTRING_LEN(string));
~~ ^~~~~~~~~~~~~~~~~~~
/usr/local/rvm/rubies/ruby-1.9.3-p551/include/ruby-1.9.1/ruby/ruby.h:674:6: note: expanded from macro 'RSTRING_LEN'
RSTRING_EMBED_LEN(str) : \
^~~~~~~~~~~~~~~~~~~~~~
/usr/local/rvm/rubies/ruby-1.9.3-p551/include/ruby-1.9.1/ruby/ruby.h:670:6: note: expanded from macro 'RSTRING_EMBED_LEN'
(long)((RBASIC(str)->flags >> RSTRING_EMBED_LEN_SHIFT) & \
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
v8_v8.cpp:22:49: warning: implicit conversion loses integer precision: 'long' to 'int' [-Wshorten-64-to-32]
V8::SetFlagsFromString(RSTRING_PTR(string), RSTRING_LEN(string));
~~ ^~~~~~~~~~~~~~~~~~~
/usr/local/rvm/rubies/ruby-1.9.3-p551/include/ruby-1.9.1/ruby/ruby.h:675:28: note: expanded from macro 'RSTRING_LEN'
RSTRING(str)->as.heap.len)
~~~~~~~~~~~~~~~~~~~~~~^~~
2 warnings generated.
compiling v8_value.cpp
clang: warning: argument unused during compilation: '-rdynamic'
v8_value.cpp:100:9: warning: unused function 'ToInt32' [-Wunused-function]
VALUE ToInt32(VALUE self) {
^
1 warning generated.
compiling v8_weakref.cpp
clang: warning: argument unused during compilation: '-rdynamic'
linking shared-object v8.bundle
clang: error: no such file or directory: '/usr/local/rvm/gems/ruby-1.9.3-p551/gems/libv8-3.3.10.4/lib/libv8/build/v8/libv8.a'
make: *** [v8.bundle] Error 1

make failed, exit code 2

Gem files will remain installed in /usr/local/rvm/gems/ruby-1.9.3-p551/gems/therubyracer-0.10.2 for inspection.
Results logged to /usr/local/rvm/gems/ruby-1.9.3-p551/extensions/x86_64-darwin-14/1.9.1/therubyracer-0.10.2/gem_make.out
An error occurred while installing therubyracer (0.10.2), and Bundler cannot continue.
Make sure that `gem install therubyracer -v '0.10.2'` succeeds before bundling.


I tried different approaches to install therubyracer like the ones mentioned in How to install therubyracer gem on 10.10 Yosemite? but still now luck.


Please help. thanks!


Share session between two rails4 applications

I am creating a application with devise. there is two domain name 1) www.test.com and 2) www.hello.com both domain pointing to same application. so I want to share session(current_user) between both app. user will login on (1) and it should access on domain(2).


Please suggest what's the best way todo it.


vendredi 27 mars 2015

'nilClass' with geocoder on rails 4

I'm trying to implement geocoder in my rails 4 app, but I'm having problems with initialization. The app properly creates, deletes, edits, etc., but when I try to implement the nearbys method in the show template I get a NoMethodError in Events#show with undefined method `each' for nil:NilClass. The app performs everything perfectly when I run it on rails 3 with attr_accessible, but right when I switch to rails 4 and change to strong parameters I get this error. I know it's something super simple, I just can't see what I'm missing.


Here's my event model:



class Event < ActiveRecord::Base
belongs_to :user
validates_presence_of :user
geocoded_by :address
after_validation :geocode, :if => :address_changed?
end


Here's my events_controller:



class EventsController < ApplicationController
before_action :authenticate_user!
load_and_authorize_resource

def index
if params[:search].present?
@events = Event.near(params[:search], 50, :order => :distance)
else
@events = Event.all
end
end

def show
end

def new
end

def edit
end

def create
@event = Event.new(event_params)
@event.user_id = current_user.id

respond_to do |format|
if @event.save
format.html { redirect_to @event, notice: 'Event was successfully created.' }
format.json { render :show, status: :created, address: @event }
else
format.html { render :new }
format.json { render json: @event.errors, status: :unprocessable_entity }
end
end
end

def update
respond_to do |format|
if @event.update(event_params)
format.html { redirect_to @event, notice: 'Event was successfully updated.' }
format.json { render :show, status: :ok, address: @event }
else
format.html { render :edit }
format.json { render json: @event.errors, status: :unprocessable_entity }
end
end
end

def destroy
@event.destroy
respond_to do |format|
format.html { redirect_to events_url, notice: 'Event was successfully destroyed.' }
format.json { head :no_content }
end
end

private
def event_params
params.require(:event).permit(:name, :event_date, :start_time, :end_time, :address, :latitude, :longitude, :description, :user_id)
end
end


Here's my show template:



<div id="header"></div>

<p>
<b>Name:</b>
<%= @event.name %>
</p>

<p>
<b>Event date:</b>
<%= @event.try(:event_date).strftime("%a, %B %d") %>
</p>

<p>
<b>Start time:</b>
<%= @event.try(:start_time).strftime("%l:%M%p") %>
</p>

<p>
<b>End time:</b>
<%= @event.try(:end_time).strftime("%l:%M%p") %>
</p>

<p>
<b>Address:</b>
<%= @event.address %>
</p>

<p>
<b>Latitude:</b>
<%= @event.latitude %>
</p>

<p>
<b>Longitude:</b>
<%= @event.longitude %>
</p>

<p>
<b>Description:</b>
<%= @event.description %>
</p>

<p>
<b>Organizer:</b>
<%= @event.user.name %>
</p>

<%= image_tag "http://ift.tt/1EeGdmH}" %>

<h3>Nearby events</h3>
<ul>
<% for event in @event.nearbys(10) %>
<li><%= link_to event.address, event %> (<%= event.distance.round(2) %> miles)</li>
<% end %>
</ul>

<%= link_to 'Edit', edit_event_path(@event) %> |
<%= link_to 'Back', events_path %>


I get the error on line 52 of the show template (for event in @event.nearbys(10)). I appreciate any help at all!


MySQL error in Ruby on Rails

Install ruby and ruby on rails on my windows 8.1


I have a problem when launching the server



C:\Sites\testing>rails s
C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/mysql2-0.3.18-x64-mingw32/lib/mysql2/mysql2.rb:2:in `require': cannot load such file -- mysql2/2.2/mysql2 (LoadError)
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/mysql2-0.3.18-x64-mingw32/lib/mysql2/mysql2.rb:2:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/mysql2-0.3.18-x64-mingw32/lib/mysql2.rb:31:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/mysql2-0.3.18-x64-mingw32/lib/mysql2.rb:31:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.9.1/lib/bundler/runtime.rb:76:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.9.1/lib/bundler/runtime.rb:76:in `block (2 levels) in require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.9.1/lib/bundler/runtime.rb:72:in `each'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.9.1/lib/bundler/runtime.rb:72:in `block in require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.9.1/lib/bundler/runtime.rb:61:in `each'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.9.1/lib/bundler/runtime.rb:61:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.9.1/lib/bundler.rb:134:in `require'
from C:/Sites/testing/config/application.rb:7:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:78:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:78:in `block in server'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:75:in `tap'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:75:in `server'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/commands.rb:17:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'


C:\Sites\testing>


Help me please. Thank.


action_dispatch.request.parameters are not being populated

I have an API sending my app requests, and the Request Payload in my Google Chrome Debugger seems populated with data that should have populated my ActionDispatch Request Parameters, so that within the controller, I could call params, and it would draw the items found in my request payload.


My request payload


stateId=resume&Authorization=&Expires=1427487450&registration%5Fid=3&member%5Fid=1&Signature=wiXiEskkMFTsOQh9vsRg%3D&Content%2DType=application%2Fjson&X%2DExperience%2DAPI%2DVersion=1%2E0%2E1&agent=null&&activityId=http%3A%2F%2F6LHIJumrnmV%5Fcourse%5Fid&content=1k21098100101100002000


So I should be able to call params['stateId'] or params['member_id'], but my params are empty. What process has to happen inbetween the Request Payload ( or simply called Form Data ), and Rails picking it up and distributing those variables as params ?


validate_presence_of on 'has_many' and 'belongs_to' association, how to write factory

I have a two models. Both having validate_presence_of .



class Company < ActiveRecord::Base
has_many :projects
validate_presence_of :projects

def save_projects(projects)
projects.each do |project|
project.company = self
project.save(:validate => false)
end
end
end


In method saving_projects(projects) is called before saving company in controller. Means I am saving company after the project.



class Project < ActiveRecord::Base
belongs_to :company
validate_presence_of :company
end


These are my models.


I am saving projects in model with validation => false. So I want to write factory for company.


What I have tried:



factory :company do
name 'Test'
user
before_create do |company|
FactoryGirl.build(:project, :company => company)
end
end


And also tried this



factory :company do
name 'Test'
user
after_build do |company|
company.projects << FactoryGirl.build(:project, :company => company)
end
end


I am getting this error:



Failure/Error: company = FactoryGirl.build(:company, :user=>user,:name => "test")
NoMethodError:
undefined method `company=' for #<Project:0x000000106c3030>


Problem track: The problem with validate_presence_of on both the model that causing issue.


rspec building new record for :has_one STI polymorphic relationship

I am upgrading a project from Rails 3.1/Ruby 1.9.3 to Rails 3.2/Ruby 2.0.0. This involves upgrading rspec from version 2.10 to 2.99 (to being with)


There are relationships set up as follows:



app/models/company.rb
require 'app_permission'
class Company < ActiveRecord::Base
has_one :supervisor_app_permission, class_name: '::SupervisorAppPermission', as: :subject, dependent: :destroy
end





app/models/app_permission.rb
class AppPermission < ActiveRecord::Base
belongs_to :subject, polymorphic: true
.
.
end
class SupervisorAppPermission < AppPermission
.
.
end


Say a company has a supervisor_app_permission in the database, within the rpsec tests any time company.supervisor_app_permission is called the supervisor_app_permission is retrieved from the database but it's being built as a new record, i.e.



company.supervisor_app_permission.new_record? is true


Similarly when updating the attributes of company.supervisor_app_permission:



company.supervisor_app_permission.update_attributes(attr: value)
results in error:
Mysql2::Error: Duplicate entry '1' for key 'PRIMARY': INSERT INTO `app_permissions`......


This only happens within the rspec tests. If I run rails console all works as expected and the code executes as expected within the app too.


Can anyone tell me why the supervisor_app_permission is being built in this within rspec?


Best RoR uploader for my use-case ( requires id in watermark, s3 storage, resque, and a separate worker-server for processing images)

I have a project that uses Ruby on Rails and currently uses Carrierwave to process file uploads. There are a couple things about the file uploads which are edge-cases and I haven't found a solution that works perfectly.



  1. the id of the image goes in the watermark. Using Carrierwave's process hook, the image has not yet been saved in active record and thus has no ID to watermark. I have gotten around this by saving the image first (which then creates the thumbs and previews) and then overwriting it again with the watermark. This does not seem efficient

  2. offloading file upload to a job on a separate server: we have a file processing server that creates zips, processes IPTC data, creates the watermarks, etc. Currently, our web server is attached to a 10 terrabyte LVM pool and our "worker" server mounts the LVM pool to process the jobs. However I would like ditch our LVM pool in favor of s3.


My (not-necessarily) ideal workflow would be:



  1. Upload a file from the frontend

  2. have backend create a photo record with no photo attached (flag the photo as not yet processed and have the frontend show a gif loader)

  3. Have backend rename the file and upload the raw file to amazon S3

  4. Have backend create a job with the photo-id and with a pointer to the raw file on S3.

  5. "worker server" picks up job, downloads raw file from S3

  6. worker server creates thumb, preview, pulls IPTC data from the raw file

  7. worker server uploads thumb, preview, and deletes the locally stored files

  8. worker server updates the photo record to indicate that the photos have been processed

  9. this is an admin-only feature and I actually don't care that the user would have to refresh the page in order to see the processed thumbnails ( i can cross the bridge when I get there )


Any ideas on this? Would carrierwave, paperclip, or dragonfly support this particular set of requirements?


combine two active record objects in Rails 3

I would like combine these two objects.



@part_group.each do |pg|
pg.available_assignments.each do |aa|
result = pg.merge(au)
end
end


However, I'm getting undefined method merge for...


How to debug assets compilation locally

I've got my css mostly written in sass, and there is a lot of it. Using a 3rd party vendor css too.


Turns out when I want to compress it, I get some errors, how does one debug those usually ?


When I execute RAILS_ENV=production rake assets:precompile --trace this happens :



** Invoke assets:precompile (first_time)
** Execute assets:precompile
** Invoke assets:precompile:all (first_time)
** Invoke assets:cache:clean (first_time)
** Invoke assets:environment (first_time)
** Execute assets:environment
** Execute assets:cache:clean
** Execute assets:precompile:all
rake aborted!
Sass::SyntaxError: Invalid CSS after ".": expected class name, was "#ff0"
(in /Users/gandalf/workspace/zazzy/app/assets/stylesheets/application-print.sass)
/Users/gandalf/.rvm/gems/jruby-1.7.19/bundler/gems/zazul-66fec84bb284/vendor/assets/stylesheets/utilities/_colors.sass:95:in `color'
/Users/gandalf/.rvm/gems/jruby-1.7.19/bundler/gems/zazul-66fec84bb284/vendor/assets/stylesheets/utilities/_colors.sass:101
/Users/gandalf/.rvm/gems/jruby-1.7.19/bundler/gems/zazul-66fec84bb284/vendor/assets/stylesheets/zazul.css.sass:28
/Users/gandalf/workspace/zazzy/app/assets/stylesheets/application-print.sass:5


How does one debug this? And how do I know once I resolved it, can I compile it on it's own? All this css works fine on development by the way, the issues is when I try to compress it. When I add config.assets.compress = true to my configuration. Any hints?


drawing directory tree of given file paths

Given array of path file : ["c:/user/brands/a.txt", "C:/rails/app/", "C:/user/alk/file"] how to draw this array to tree directory in ruby console like this: C--user--alk--file |----|---brands--a.txt ---rails--app thanks


seeds.rb utf-8? And how to fill table without model?

I've got some problems with my seeds.rb file in my ruby on rails application.


Wen I prefill the database with the seeds.rb file I got this error when I start my application:



incompatible character encodings: UTF-8 and ASCII-8BIT


But the seeds.rb file is utf8 ... When I preffil with phpmyadmin all works fine.


Second Problem is how can I prefill a table which dosn't has a model?


RUBY ON RAILS PRODUCTION environment, CANNOT CLEAR CACHE

Is there a way to clear cache in "production environment"


using the default cache of rails


I tried using "caches_action :index, :expires_in => 1.minute" but it only works on development environment but not in production


How to pass ransack param[:q] object to another method in rails

I am trying to pass my ransack params[:q] object to my presenter class but getting the No Ransack::Search object was provided to search_form_for! error.


Here is my sample code


client_managers_widgets/index.html.haml



= search_form_for @search, :url => admin_client_managers_widgets_path do |f|
= render :partial => "admin/share/filter_wrapper", :locals => { :f => f, :filter=> "admin/client_managers_widgets/filters/redemption_filter" }


_redemption_filter.html.haml



%table.filters
%tr
%td
= f.label :created_at_gteq, "Select Period"
= f.select :created_at_gteq, { "Start Till Date" => "", "This Year" => Date.today.beginning_of_year, "Last Month" => 1.month.ago.beginning_of_month, "This Month" => Date.today.beginning_of_month }
%td
= f.label :user_telecom_circle_regional_managers_id_eq, "Region"
= f.collection_select :user_telecom_circle_regional_managers_id_eq, @telecom_regions.select_options, :id, :region, {:include_blank => t(:all)}, :class => 'telecom_circle_regional_managers_id_eq'
%tr
%td
= f.label :created_at_date_gteq,"Select Custome Time"
= f.text_field :created_at_date_gteq, :class => 'datepicker input-small'
= f.label "-", :class=>"to"
= f.text_field :created_at_date_lteq, :class => 'datepicker input-small'


controller => client_managers_widgets



def index
@client_manager_dashboard = ClientManagerDashboard.new(current_admin_user, search_params)
# .
# .
# .
end

private

def search_params
params[:q]
end


presenter => client_manager_dashboard



class ClientManagerDashboard
def initialize(admin_user, search_params)
@current_ability = Ability.new(admin_user)
@search_params = search_params
end

def get_users
@search = User.joins(:client).where(clients: {id: clients}).search(search_params)
@users = @search.result
end
private

def current_ability
@current_ability
end

def search_params
@search_params
end
end

Callback in Rails

I want to call a function after a particular form is submitted in my mobile app. I am calling it as :



after_save :insert_into_my_table, on: :save_playing_request


save_playing_request is the function which saves the new form. I want to call insert_into_my_table after this. Is it the correct way?


jeudi 26 mars 2015

How to solve ArgumentError using rails 3?

I am trying to do edit profile in my app.When i inserted the new setting and updating it it is giving me the below error.


Error:



wrong number of arguments (1 for 0)
Rails.root: C:/Site/library_management1

Application Trace | Framework Trace | Full Trace
app/controllers/homes_controller.rb:148:in `updatedata'


My codes are as follows


views/homes/userprofile.html.erb



<% if current_user %>
<div class="totaldiv">
<div class="navdiv"><span>STUDENT INFORMATION</span><span>Logged in as <%= current_user.email %></span></div>
<div class="wrapper">
<div id="leftsidebtn">
<ul>
<li><a href="/homes/issuebooks">Book issue</a></li>
<li><a href="/homes/availablebooks">Books Available</a></li>
<li><a href="/homes/magazines?user_id=<%= current_user.id %>">Magazines Purchase</a></li>
<li><a href="/homes/newspaper">Newspaper Purchase</a></li>
<li><a href="/homes/userprofile">Profile settings</a></li>
<li><a href="/homes/blog">My Blog</a></li>
<li><a href="/sessions/removeuser">Log Out</a></li>
</ul>
</div>
</div>
<div class="restdiv" id="ex3" >
<center>
<div class="edit-profile"><button type="button" class="btn btn-success" id="btnShowModal" >Edit Your Profile</button></div>
<div id="output"></div>

<div id="overlay" class="web_dialog_overlay"></div>
<div id="dialog" class="web_dialog">
<div class="edit-firstdiv">
<div class="web_dialog_title align_right">
<a href="#" id="btnClose">Close</a>
</div>
<%= form_for :users,:url => {:action => 'updatedata',:id => params[:id] } do |f| %>
<% if @users.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@users.errors.count, "error") %> prohibited this post from being saved:</h2>

<ul>
<% @users.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="edit-firstname">
<label for="first_name">First Name</label>
<%= f.text_field :first_name,:id => 'first_name',:value => @users.first_name %>
</div>
<div class="edit-lastname">
<label for="last_name">Last Name</label>
<%= f.text_field :last_name,:id => 'first_name',:value => @users.last_name %>
</div>
<div class="edit-emailid">
<label for="emailid">Emailid</label>
<%= f.email_field :email,:id => 'first_name',:value => @users.email %>
</div>
<div class="edit-password">
<label for="password">Password</label>
<%= f.password_field :password,:id => 'first_name',:value => @users.password %>
</div>
<div class="edit-confirm">
<label for="Address">Password again</label>
<%= f.password_field :password_confirmation,:id => 'first_name' %>
</div>
<div class="edit-telephone">
<label for="phone">Phone no</label>
<%= f.telephone_field :tel_no,:id => 'first_name',:value => @users.tel_no %>
</div>
<div class="edit-address">
<label for="Address">Address</label>
<%= f.text_area :address,:class => 'address_text',:value => @users.address %>
<textarea id="first_name"></textarea>
</div>
<div class="edit-submit">
<%= f.submit 'Update Data',:class => 'btn btn-success' %>
</div>
</div>
<% end %>
</div>
</center>
</div>
</div>
<% end %>


controller/homes_controller.rb



class HomesController < ApplicationController
before_filter :authenticate_admin!,only: [:admin]
def index

end
def admin

end
def managebooks
@books=Book.new
if params[:id]
@books=Book.find(params[:id])
@book=Book.all
end
end
def savebooks
@books=Book.new(params[:books])
if @books.save
flash[:notice]="Data has submitted successfully"
flash[:color]="valid"
redirect_to :action => 'managebooks',:id => @books.id
else
flash[:notice]="Data couldnot submitted successfully"
flash[:color]="invalid"
render 'managebooks'
end
end
def remove
@books=Book.find(params[:id])
@books.destroy
end
def books

end
def showbooks
@books=Book.all
end
def searchbooks
@books=Book.all
end
def member
@users=User.new
end
def registration
@users=User.new
end
def savedata
@users=User.new(params[:users])
if @users.save
flash[:notice]="Data has submitted successfully"
flash[:color]="valid"
redirect_to :action => 'member'
else
flash[:notice]="Data could not submitted successfully"
flash[:color]="invalid"
render 'registration'
end
end
def issuebooks
@issues=Issue.new
end
def savedissuebooks
@issues=Issue.new(params[:issues])
if @issues.save
flash[:notice]="information has saved successfully"
flash[:color]="valid"
redirect_to :action => 'member'
else
flash[:notice]="Data couldnot saved"
flash[:color]="invalid"
render 'issuebooks'
end
end
def availablebooks

@books=Book.all
end
def userissues
@issues=Issue.all
end
def magazine
@magazines=Magazine.new
end
def savemagazines
@users=User.find(params[:id])
@magazines=Magazine.new(params[:magazines])
@magazines.user_id=@users.id
if @magazines.save
flash[:notice]="Data submitted successfully"
flash[:color]="valid"
redirect_to :action => "member"
else
flash[:notice]="Data could not saved"
flash[:color]="invalid"
render 'magazines'
end
end
def magazineissue
@magazines=Magazine.all
@users=User.find @magazines.first.user_id
end
def blog
@blogs=Blog.new
end
def savecomments
@users=User.find(params[:id])
@blogs=Blog.new(params[:blogs])
@blogs.user_id=@users.id
if @blogs.save
flash[:notice]="Comment has been posted successfully"
flash[:color]="valid"
redirect_to :action => "showcomment"
else
flash[:notice]="Comment could not saved"
flash[:color]="invalid"
render 'blog'
end
end
def showcomment
@blogs=Blog.all
end
def newspaper
@newspapers=Newspaper.new
end
def savenewspaper
@users=User.find(params[:id])
@newspapers=Newspaper.new(params[:newspapers])
@newspapers.user_id=@users.id
if @newspapers.save
flash[:notice]="newspaper data saved successfully"
flash[:color]="valid"
redirect_to :action => "member"
else
flash[:alert]="Data could not saved successfully"
flash[:color]="invalid"
render 'newspaper'
end
end
def adminnewspaperissue
@newspapers=Newspaper.all
@users=User.find @newspapers.first.user_id
end
def userprofile
@users=User.find(params[:id])
end
def updatedata
@users=User.find(params[:id])
if @users.update_attributes(params(:users))
flash[:notice]="User Data has updated"
flash[:color]="valid"
redirect_to :action => 'member'
else
flash[:alert]="Data could not updated"
flash[:color]="invalid"
render 'userprofile'
end
end
end


Please check my code and let me to know where i did mistake and what should be the solution.