I am using has_ancestry, I have imported a csv file that includes deep nesting and it used textbox1 as an attribute. I would like to be able to apply my hierarchy based on this attribute.
dimanche 31 mai 2015
Unable to run LOOPS within Javascript Ruby on Rails View
Executive Summary
-
Question 1: What is the value of providing local variables to a render, when they can access the instance objects in the controller?
-
Issue: I can NOT run a ruby loop within my _error.js.erb file. The goal of this loop is to provide DIRECT output to a $("#error_explanation") id regarding all of the
-
I was able to run the various other jquery commands as illustrated below.
-
I am able to run straight JQUERY commands leveraging ruby.
Dear Friends,
In my create controller, i have a
format.js { render "_error.js.erb", locals: {post: @post, errors: @post.errors.messages} }
In my VIEW _error.js.erb, i have 3 JQUERY queries, two of them work, but the third does not work.
This Works. $("#error_explanation").append('<%= j pluralize(post.errors.count, "error") %> prohibited this secret from being saved: <p>');
This Works. $("#error_explanation").append('<%= post.errors.full_messages_for(:title) %>');
This Does NOT Work. $("#error_explanation").append('
<% post.errors.messages.each do |error| %>
<%= j error %>
<% end %>');
I can only assume that it is because of my loop? Can I not perform loops in my javascript (js.erb) code?
has_ancestry/ assigning hierarchy to existing table
I have a database that is imported from a CSV file and I would like to assign hierarchy based on the assembly level below. not sure which approach to take. I can write if statements but it will be very long. sorry I am new to this, and I don't know where to begin. any help is much appreciated.
assembly_level assembly_tree description uniq_id
0 zero level "zero level" d9s64
1 level one assembly "level one" c9633
2 level two assembly "level two" 11197
3 level three assembly "level three" e271f
4 level four assembly "level four" 552da
4 level four assembly "level four" 4568a
3 level three assembly "level three" b72bd
edit
who can I assign assembly_level to Parent_id during import?
@item = Item.new(:assembly_level=> params[:parent_id])
ActiveRecord::RecordNotFound / Couldn't find Maker with 'id'=1
I might've erased my user information (:maker_id, :name, and :password) when I did rake db:reset in terminal, so now going to 'localhost:3000' '/' gives me this error:
ActiveRecord::RecordNotFound in PagesController#home
Couldn't find Maker with 'id'=1
Extracted source (around line #7):
6 def current_user
7 @current_user ||= Maker.find(session[:maker_id]) if session[:maker_id]
8 end
9 helper_method :current_user
My application controller has:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def current_user
@current_user ||= Maker.find(session[:maker_id]) if session[:maker_id]
end
helper_method :current_user
def authorize
redirect_to '/' unless current_user
end
end
My pages controller has an empty
def home
end
My pages home.html.erb view has:
<div class='text-center'>
<h1>Welcome to venture</h1>
<br><br>
<%= link_to "Signup", '/signup', class: 'btn btn-success' %> or
<%= link_to "Login", '/login', class: 'btn btn-primary' %>
</div>
My layouts application.html.erb view has:
<body class="containter">
<div class='pull-right'>
<% if current_user %>
Logged in as <%= current_user.name %> | <%= link_to "Logout", '/logout' %>
<% else %>
<%= link_to "Signup", '/signup'%> or <%= link_to "Login", '/login' %>
<% end %>
</div>
<h1><%= link_to 'venture', '/' %></h1>
<% flash.each do |type, message| %>
<div class="alert alert-info fade in">
<button class="close" data-dismiss="alert">×</button>
<%= message %>
</div>
<% end %>
<%= yield %>
</body>
It used to work before the db:reset which runs db:drop db:setup I believe. Usually I would just create users through the signup page but now I cannot get there.
Any insight is appreciated.
Ruby On rails validations
I am new to Rails.
I Have create a simple rails page which accepts bookid, title and publisher
rails generate scaffold book bookid:string title:string publisher:string
I have written a new search.html.erb and a defination to it which search for books by title.
Now my Question is how do i give a custom message if that book details doesn't exist in database.
Ex : I gave book name as rails it doesn't have any entry in my database
it should give message No Such Books
samedi 30 mai 2015
Capistrano 3 - Cap Production Deploy Error
I am trying to run a production deploy. On server, I got this message:
SSHKit::Runner::ExecuteError: Exception while executing on host 172.31.47.95: exit
/home/ec2-user/.rvm/gems/ruby-2.1.3/gems/capistrano-3.1.0/lib/capistrano/tasks/git.rake:28:in `exit'
/home/ec2-user/.rvm/gems/ruby-2.1.3/gems/capistrano-3.1.0/lib/capistrano/tasks/git.rake:28:in `block (4 levels) in '
/home/ec2-user/.rvm/gems/ruby-2.1.3/gems/sshkit-1.5.1/lib/sshkit/backends/abstract.rb:85:in `with'
/home/ec2-user/.rvm/gems/ruby-2.1.3/gems/capistrano-3.1.0/lib/capistrano/tasks/git.rake:27:in `block (3 levels) in '
/home/ec2-user/.rvm/gems/ruby-2.1.3/gems/sshkit-1.5.1/lib/sshkit/backends/netssh.rb:54:in `instance_exec'
/home/ec2-user/.rvm/gems/ruby-2.1.3/gems/sshkit-1.5.1/lib/sshkit/backends/netssh.rb:54:in `run'
/home/ec2-user/.rvm/gems/ruby-2.1.3/gems/sshkit-1.5.1/lib/sshkit/runners/parallel.rb:13:in `block (2 levels) in execute'
SystemExit: exit
/home/ec2-user/.rvm/gems/ruby-2.1.3/gems/capistrano-3.1.0/lib/capistrano/tasks/git.rake:28:in `exit'
/home/ec2-user/.rvm/gems/ruby-2.1.3/gems/capistrano-3.1.0/lib/capistrano/tasks/git.rake:28:in `block (4 levels) in '
/home/ec2-user/.rvm/gems/ruby-2.1.3/gems/sshkit-1.5.1/lib/sshkit/backends/abstract.rb:85:in `with'
/home/ec2-user/.rvm/gems/ruby-2.1.3/gems/capistrano-3.1.0/lib/capistrano/tasks/git.rake:27:in `block (3 levels) in '
/home/ec2-user/.rvm/gems/ruby-2.1.3/gems/sshkit-1.5.1/lib/sshkit/backends/netssh.rb:54:in `instance_exec'
/home/ec2-user/.rvm/gems/ruby-2.1.3/gems/sshkit-1.5.1/lib/sshkit/backends/netssh.rb:54:in `run'
/home/ec2-user/.rvm/gems/ruby-2.1.3/gems/sshkit-1.5.1/lib/sshkit/runners/parallel.rb:13:in `block (2 levels) in execute'
Tasks: TOP => git:check
(See full trace by running task with --trace)
The deploy has failed with an error: #
However, when I try to run it on my local project folder, I get this error instead: LoadError: cannot load such file -- rvm1/capistrano3 /Users/administrator/Desktop/CitySpade/Capfile:22:in <top (required)>' /Library/Ruby/Gems/2.0.0/gems/capistrano-3.1.0/lib/capistrano/application.rb:24:in
load_rakefile' /Library/Ruby/Gems/2.0.0/gems/capistrano-3.1.0/lib/capistrano/application.rb:15:in run' /Library/Ruby/Gems/2.0.0/gems/capistrano-3.1.0/bin/cap:3:in
' /usr/bin/cap:23:in load' /usr/bin/cap:23:in
'
Can someone help? Thank you so much!
Rails Convert UNIX timestamp to SQL DateTime
I have timestamp as "1432927800000"
I want to save it in DateTime column of MySQL. (SQL DateTime column stores date in this format : 2010-06-24 11:30:00)
I have tried
uTime = params[:fromDate] #contains "1432927800000"
Date.new(uTime).to_formatted_s(:db) #Comparison of String with 0 failed.
DateTime.strptime("1318996912",'%s') #Give weird date: Wed, 03 Sep 47377 12:00:00 +0000
Date.parse(uTime).to_s(:db) #Invalid Date
I am expecting 2015-5-30 1:00:00 from "1432927800000"
use engine routes instead of main app(wrapper app)
I am implementing rails
app in which I have a rails engine
as well.
In main app I have a model Marks
class Mark < ActiveRecord::Base
end
Rake routes for Mark
is (simple and index page url)
mark_path(`)
Url for this /marks/
and inside the engine
also there is a model Mark
.
class Test::Mark < ActiveRecord::Base
end
For engine
marks_path
Url for Engine
/test/marks/1
Query
So how can access engine
marks_path
in engine's
model. Currently when use the url_helper
in model it return main app
routes instead of engine routes
.
But I need engine
routes.
vendredi 29 mai 2015
ruby on rails undefined method
sharvil@sharvil:~/railstut/blog$ rails c
Loading development environment (Rails 4.2.1)
2.2.2 :001 > q=Question.all
Question Load (0.5ms) SELECT `questions`.* FROM `questions`
=> #<ActiveRecord::Relation [#<Question questions_id: 1, question: "What is this", almuni_almuni_id: 1, category_category_id: 1>]>
2.2.2 :002 > q
=> #<ActiveRecord::Relation [#<Question questions_id: 1, question: "What is this", almuni_almuni_id: 1, category_category_id: 1>]>
2.2.2 :003 > q.question
NoMethodError: undefined method `question' for #<Question::ActiveRecord_Relation:0x000000045dc178>
from /home/sharvil/.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/relation/delegation.rb:136:in `method_missing'
I am getting a error in accessing q.questions .. question is column in table.
pls help.
Rails Trying to access perameters in Model
I've created a User model through Devise gem
My relationships are setup as:
- The User has a many to many relationship with Role
- The User belongs_to (one to many relationship with) Batch
- The User has_one (one to one relationship with) UserProfile
Now everytime a User is created I am calling the method cup that creates a UserProfile as well. The problem is that I can't access anything other then devise's own perameters in the Model.
For example I have a drop down to select for Role but i cant access its selected value
My aim is to do something like:
def cup
if role.title == 'this'
create_user_profile(:username => 'username01')
else
create_user_profile(:username => 'username02')
end
end
This is what the model looks like:
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
belongs_to :batch
has_one :user_profile
after_create :cup
def cup
create_user_profile(:username => 'username')
end
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
My parameters look like this:
{"utf8"=>"✓", "authenticity_token"=>"TbsLJxZB2aeDgj8RitTRKURCc3KODCKpv/xphwhAaIw=", "users"=>{"username"=>"rfdsfew", "role_id"=>"1", "batch_id"=>"1"}, "user"=>{"email"=>"2@223.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
I can access the params in user hash but not in users hash
My guess is that, this is because the users hash is not allowed in devise controller, since I can't access devise's controller I have no idea how to permit the users hash.
And I found this on the internet but it didn't work:
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :username
end
no implicit conversion of nil into String (sponsorship )
I am getting the above error and it says that it has to do with the "+". Please note I did not code the below page, but I was told to fix it. If someone could help that would be awesome.
Sponsorship Controller
class SponsorshipController < ApplicationController
def index
@title = "Child Sponsorship: Help Children in Haiti by Becoming a Sponsor"
@meta = "Help a child in Haiti who is in need through sponsorship. Sponsorship provides children with food, care, clothing, shelter & education. Sponsor a child in Haiti today."
@txtname = params[:fname]
@txtemail = params[:email]
@txtstreet = params[:address]
@txtcity = params[:city]
@txtstate = params[:state]
@txtzip = params[:zip]
if @txtname.nil? || @txtname == '' || @txtstreet.nil? || @txtstreet == '' || @txtcity.nil? || @txtcity == '' || @txtstate.nil? || @txtstate == '' || @txtzip.nil? || @txtzip == ''
@isvalid = false
@testrequest='first time'
else
@isvalid = true
@prefs = " "
if !params[:prefgirl].nil?
@prefs = "Girl,"
end
if !params[:prefboy].nil?
@prefs = @prefs + 'Boy,';
end
if !params[:prefkinder].nil?
@prefs = @prefs + 'Kindergarten,';
end
if !params[:prefgrade].nil?
@prefs = @prefs + 'Grade School,';
end
if !params[:prefhigh].nil?
@prefs = @prefs + 'High School';
end
@data = {
:childpreferences => @prefs,
:fname => params[:fname],
:phone => params[:phonenumber],
:fromaddress => params[:email],
:streetaddress => params[:address],
:city => params[:city],
:state => params[:state],
:zip => params[:zip]
}
@testrequest = @prefs
ContactUsMailer.sponsorship_contact(@data).deliver
ContactUsMailer.sponsorship_thankyou(@data).deliver
end
respond_to do |format|
format.html {render :layout=>"homeLayout"}# haiti_one.html.erb
end
end
def say_yes
@title='Say Yes! Sponsor a Child Today!'
respond_to do |format|
format.html {render :layout=>"homeLayout"}
end
end
end
FULL TRACE
app/controllers/mymoh_controller.rb:213:in +' app/controllers/mymoh_controller.rb:213:in
sponsorships' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_controller/metal/implicit_render.rb:4:in send_action' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/abstract_controller/base.rb:167:in
process_action' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_controller/metal/rendering.rb:10:in process_action' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/abstract_controller/callbacks.rb:18:in
block in process_action' vendor/bundle/ruby/2.1.0/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:425:in _run__3687996442544047678__process_action__3216127983448203575__callbacks' vendor/bundle/ruby/2.1.0/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:405:in
__run_callback' vendor/bundle/ruby/2.1.0/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:385:in _run_process_action_callbacks' vendor/bundle/ruby/2.1.0/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:81:in
run_callbacks' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/abstract_controller/callbacks.rb:17:in process_action' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_controller/metal/rescue.rb:29:in
process_action' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_controller/metal/instrumentation.rb:30:in block in process_action' vendor/bundle/ruby/2.1.0/gems/activesupport-3.2.11/lib/active_support/notifications.rb:123:in
block in instrument' vendor/bundle/ruby/2.1.0/gems/activesupport-3.2.11/lib/active_support/notifications/instrumenter.rb:20:in instrument' vendor/bundle/ruby/2.1.0/gems/activesupport-3.2.11/lib/active_support/notifications.rb:123:in
instrument' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_controller/metal/instrumentation.rb:29:in process_action' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_controller/metal/params_wrapper.rb:207:in
process_action' vendor/bundle/ruby/2.1.0/gems/activerecord-3.2.11/lib/active_record/railties/controller_runtime.rb:18:in process_action' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/rails3/action_controller.rb:23:in
block in process_action' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/controller_instrumentation.rb:353:in perform_action_with_newrelic_trace' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/rails3/action_controller.rb:22:in
process_action' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/abstract_controller/base.rb:121:in process' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/abstract_controller/rendering.rb:45:in
process' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_controller/metal.rb:203:in dispatch' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_controller/metal/rack_delegation.rb:14:in
dispatch' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_controller/metal.rb:246:in block in action' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/routing/route_set.rb:73:in
call' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/routing/route_set.rb:73:in dispatch' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/routing/route_set.rb:36:in
call' vendor/bundle/ruby/2.1.0/gems/journey-1.0.4/lib/journey/router.rb:68:in block in call' vendor/bundle/ruby/2.1.0/gems/journey-1.0.4/lib/journey/router.rb:56:in
each' vendor/bundle/ruby/2.1.0/gems/journey-1.0.4/lib/journey/router.rb:56:in call' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/routing/route_set.rb:601:in
call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/rack/agent_hooks.rb:30:in
traced_call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/rack/browser_monitoring.rb:23:in
traced_call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in call' vendor/bundle/ruby/2.1.0/gems/exception_notification-4.0.0/lib/exception_notification/rack.rb:28:in
call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in call' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/best_standards_support.rb:17:in
call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in call' vendor/bundle/ruby/2.1.0/gems/rack-1.4.5/lib/rack/etag.rb:23:in
call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in call' vendor/bundle/ruby/2.1.0/gems/rack-1.4.5/lib/rack/conditionalget.rb:25:in
call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in call' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/head.rb:14:in
call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in call' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/params_parser.rb:21:in
call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in call' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/flash.rb:242:in
call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in call' vendor/bundle/ruby/2.1.0/gems/rack-1.4.5/lib/rack/session/abstract/id.rb:210:in
context' vendor/bundle/ruby/2.1.0/gems/rack-1.4.5/lib/rack/session/abstract/id.rb:205:in call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in
call' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/cookies.rb:341:in call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in
call' vendor/bundle/ruby/2.1.0/gems/activerecord-3.2.11/lib/active_record/query_cache.rb:64:in call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in
call' vendor/bundle/ruby/2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/abstract/connection_pool.rb:479:in call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in
call' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/callbacks.rb:28:in block in call' vendor/bundle/ruby/2.1.0/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:405:in
_run__790379348702901205__call__4407048364405463113__callbacks' vendor/bundle/ruby/2.1.0/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:405:in __run_callback' vendor/bundle/ruby/2.1.0/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:385:in
_run_call_callbacks' vendor/bundle/ruby/2.1.0/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:81:in run_callbacks' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/callbacks.rb:27:in
call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in call' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/remote_ip.rb:31:in
call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in call' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/debug_exceptions.rb:16:in
call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in call' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/show_exceptions.rb:56:in
call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in call' vendor/bundle/ruby/2.1.0/gems/railties-3.2.11/lib/rails/rack/logger.rb:32:in
call_app' vendor/bundle/ruby/2.1.0/gems/railties-3.2.11/lib/rails/rack/logger.rb:16:in block in call' vendor/bundle/ruby/2.1.0/gems/activesupport-3.2.11/lib/active_support/tagged_logging.rb:22:in
tagged' vendor/bundle/ruby/2.1.0/gems/railties-3.2.11/lib/rails/rack/logger.rb:16:in call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in
call' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/request_id.rb:22:in call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in
call' vendor/bundle/ruby/2.1.0/gems/rack-1.4.5/lib/rack/methodoverride.rb:21:in call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in
call' vendor/bundle/ruby/2.1.0/gems/rack-1.4.5/lib/rack/runtime.rb:17:in call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in
call' vendor/bundle/ruby/2.1.0/gems/activesupport-3.2.11/lib/active_support/cache/strategy/local_cache.rb:72:in call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in
call' vendor/bundle/ruby/2.1.0/gems/rack-1.4.5/lib/rack/lock.rb:15:in call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in
call' vendor/bundle/ruby/2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/static.rb:62:in call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in
call' vendor/bundle/ruby/2.1.0/gems/rack-cache-1.2/lib/rack/cache/context.rb:136:in forward' vendor/bundle/ruby/2.1.0/gems/rack-cache-1.2/lib/rack/cache/context.rb:245:in
fetch' vendor/bundle/ruby/2.1.0/gems/rack-cache-1.2/lib/rack/cache/context.rb:185:in lookup' vendor/bundle/ruby/2.1.0/gems/rack-cache-1.2/lib/rack/cache/context.rb:66:in
call!' vendor/bundle/ruby/2.1.0/gems/rack-cache-1.2/lib/rack/cache/context.rb:51:in call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in
call' vendor/bundle/ruby/2.1.0/gems/rack-timeout-0.2.4/lib/rack/timeout.rb:108:in call' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in
call' vendor/bundle/ruby/2.1.0/gems/railties-3.2.11/lib/rails/engine.rb:479:in call' vendor/bundle/ruby/2.1.0/gems/railties-3.2.11/lib/rails/application.rb:223:in
call' vendor/bundle/ruby/2.1.0/gems/railties-3.2.11/lib/rails/railtie/configurable.rb:30:in method_missing' vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.11.2.286/lib/new_relic/agent/instrumentation/middleware_tracing.rb:67:in
call' vendor/bundle/ruby/2.1.0/gems/rack-1.4.5/lib/rack/content_length.rb:14:in call' vendor/bundle/ruby/2.1.0/gems/railties-3.2.11/lib/rails/rack/log_tailer.rb:17:in
call' vendor/bundle/ruby/2.1.0/gems/thin-1.6.3/lib/thin/connection.rb:86:in block in pre_process' vendor/bundle/ruby/2.1.0/gems/thin-1.6.3/lib/thin/connection.rb:84:in
catch' vendor/bundle/ruby/2.1.0/gems/thin-1.6.3/lib/thin/connection.rb:84:in pre_process' vendor/bundle/ruby/2.1.0/gems/thin-1.6.3/lib/thin/connection.rb:53:in
process' vendor/bundle/ruby/2.1.0/gems/thin-1.6.3/lib/thin/connection.rb:39:in receive_data' vendor/bundle/ruby/2.1.0/gems/eventmachine-1.0.7/lib/eventmachine.rb:187:in
run_machine' vendor/bundle/ruby/2.1.0/gems/eventmachine-1.0.7/lib/eventmachine.rb:187:in run' vendor/bundle/ruby/2.1.0/gems/thin-1.6.3/lib/thin/backends/base.rb:73:in
start' vendor/bundle/ruby/2.1.0/gems/thin-1.6.3/lib/thin/server.rb:162:in start' vendor/bundle/ruby/2.1.0/gems/rack-1.4.5/lib/rack/handler/thin.rb:13:in
run' vendor/bundle/ruby/2.1.0/gems/rack-1.4.5/lib/rack/server.rb:268:in start' vendor/bundle/ruby/2.1.0/gems/railties-3.2.11/lib/rails/commands/server.rb:70:in
start' vendor/bundle/ruby/2.1.0/gems/railties-3.2.11/lib/rails/commands.rb:55:in block in <top (required)>' vendor/bundle/ruby/2.1.0/gems/railties-3.2.11/lib/rails/commands.rb:50:in
tap' vendor/bundle/ruby/2.1.0/gems/railties-3.2.11/lib/rails/commands.rb:50:in <top (required)>' script/rails:6:in
require' script/rails:6:in `'
New Relic and Rails app, she slow part in the output
I have a Rails application with the following output from the New Relic app:
Category Segment % Time Avg calls (per txn) Avg time (ms)
Controller Api::PostsController#index 94.5 1.0 399
ActiveRecord Combination#find 1.6 0.385 6.58
ActiveRecord Post#find 1.1 1.62 4.64
ActiveRecord User#find 0.8 2.23 3.56
ActiveRecord Tag#find 0.5 1.38 2.12
ActiveRecord Vote#find 0.4 1.36 1.54
ActiveRecord Comment#find 0.3 1.0 1.23
ActiveRecord Photo#find 0.3 1.0 1.3
ActiveRecord PostTag#find 0.3 1.0 1.19
ActiveRecord UserBadge#find 0.2 1.0 0.995
Database SQL - SELECT 0.0 0.59 0.162
If all active record queries are only 5% of the time, where can be the other 95% of the time? I have cache in my app but for now it's not Redis, but it's File Store cache. Is it possible 95% of the time to be fetching the data from the File Store Cache?
Load associations to one level while conditionally sideloading associations in Active model serializers
AMS version 0.8.3,
I created a base_serializer.rb like this and extended the same.
class BaseSerializer < ActiveModel::Serializer
def include_associations!
if @options[:embed]
embed = @options[:embed].split(',').map{|item| item.strip.to_sym}
embed.each do |assoc|
include! assoc if _associations.keys.include?(assoc)
end
end
end
end
class EventSerializer < BaseSerializer
attributes :id, :name
has_many :organizers, serializer: OrganizerSerializer
has_many :participants, serializer: ParticipantSerializer
end
class OrganizerSerializer < BaseSerializer
attributes :id, :name
has_many :related, serializer: RelatedSerializer
end
class ParticipantSerializer < BaseSerializer
attributes :id, :name
has_many :related, serializer: RelatedSerializer
end
class RelatedSerializer < BaseSerializer
attributes :id, :name
has_many :something, serializer: SomethingSerializer
end
and the index method in EventsController is written as
# GET /events?embed=organizers,participants
def index
@events = Event.all
render json: @events, embed: params[:embed]
end
With this I can get the :id and :name of events, organizers and participants. But, I want the attributes of related association as well. I don't need details of something serializer. I want to go till this level for each association. How can I achieve that?
Ruby : Dynamic Inheritance
I have two base class and multiple child class.. Based on the type, the child class dynamically inherit from the base parent class.
Eg:
class Dad
def initialize
#initialize some stuffs
end
end
class Mom
def initialize
#initialize some stuffs
end
end
class child
def initialize
super
#initialize some stuffs
end
end
class child2
def initialize
super
#initialize some stuffs
end
end
class child3
end
How to assign parent class to child class dynamically?
Difference between a || a = b and a = a || b in ruby?
Can anyone put light on this expression. Seems like both are same but they are not.
a || a = b or a ||= b
and
a = a || b
if
a = 4 and b = 6, output is always 4
This always confuse and misconcept me. Can someone please explain it?
jeudi 28 mai 2015
Please convert this query
"SELECT results.id, results.name, results.contact_phone, results.contact_email, results.verified_phone, results.verified_email, results.location_id, results.distance_in_km FROM (
SELECT bands.id, bands.name,
IF(bands.contact_phone > '', 'yes', 'no') AS contact_phone,
IF(bands.contact_email > '', 'yes', 'no') AS contact_email,
IF(bands.verified_phone=1, 'yes', 'no') AS verified_phone,
IF(bands.verified_email=1, 'yes', 'no') AS verified_email,
tags.name AS genre, locations.id AS location_id, p.*,
ROUND((6378.10 * ACOS(COS(RADIANS(latpoint))
* COS(RADIANS(`lat`))
* COS(RADIANS(longpoint) - RADIANS(`long`))
+ SIN(RADIANS(latpoint))
* SIN(RADIANS(`lat`)))), 0) AS distance_in_km
FROM gigrep_promo_#{Rails.env}.taggings
INNER JOIN gigrep_promo_#{Rails.env}.tags ON taggings.tag_id=tags.id
INNER JOIN gigrep_promo_#{Rails.env}.bands ON taggings.taggable_id=bands.id
INNER JOIN gigrep_promo_#{Rails.env}.locations ON bands.location_id=gigrep_promo_#{Rails.env}.locations.id
JOIN (SELECT `lat` AS latpoint, `long` AS longpoint FROM gigrep_promo_#{Rails.env}.locations WHERE id=#{location_id} LIMIT 1) AS p
WHERE context = 'genres'
AND taggable_type = 'Band'
#{genres_where}
GROUP BY bands.name
ORDER BY IF(distance_in_km IS NULL, 999999999, distance_in_km), bands.name
) AS results"
Rails: ActiveRecord::RecordNotFound in Cart
I user friendly_id for all the items. I am getting an error in the cart.rb model saying .. Couldn't find Product with 'id'=the-pen
I'm unsure what to do. Any help would be appreciated
cart.rb
class CartItem < ActiveRecord::Base
attr_reader :product_id, :quantity
def initialize product_id, quantity = 1
@product_id = product_id
@quantity = quantity
end
def increment
@quantity = @quantity + 1
end
def product
Product.find product_id
end
def total_price
product.price * quantity
end
end
CartsController.rb
class CartsController < ApplicationController
before_filter :initialize_cart
def add
@cart.add_item params[:id]
session["cart"] = @cart.serialize
@product = Product.friendly.find(params[:id])
redirect_to :back, notice: "Added #{@product.title} to cart"
end
def show
end
def checkout
@order_form = OrderForm.new user: User.new
end
end
ApplicationController.rb
def initialize_cart
@cart = Cart.build_from_hash session
end
views/cart/show.html.erb
<% @cart.items.each do |item| %>
<%=link_to item.product.title, item.product %>
<%= item.quantity %>
<%= @cart.total_price %>
Could not find gem 'rails x86-mingw32'
I'm doing the Rails Tutorial by Michael Hartl and I ran into this problem when trying to run the rails server.
This is is my gem file
gem 'rails', '4.1.5'
gem 'sqlite3'
gem 'sass-rails', '~> 4.0.3'
gem 'uglifier', '>= 1.3.0
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0',
gem 'tzinfo-data', platforms: [:mingw, :mswin]
I am trying to run a rails class file locally but what is the command to launch?
I am trying to run a scraper/spider class locally, or on a server, but what's the correct command to launch it?
For example, if the spider's name is newyorkhomes.rb and has the following: module Spider module Feeds class NewYorkHomes < Spider::Feeds::Base
When I switch into the the directory containing the file, I tried to run the following: load 'newyorkhomes.rb' and ruby 'newyorkhomes.rb' but neither worked
bundle exec newyorkhomes.rb doesn't work either
should I execute it locally or on a server? I can change my directory into the file containing these scraper tasks on a server but the server doesn't support that many commands there
Rake running all my invokes after task block
As outlined in a previous question, I'm trying to get my testing database to reset properly between runs of each of our three suites: Units, functionals, and integration. These suites run without a problem individually, as the database is cleared beforehand, but for some reason this doesn't happen when running all three in succession using rake test
.
So what does a complete newbie to Rails-flavored Rake do? He tries to futz with it by making his own version of rake test
where the reset-between-suites does happen, guided somewhat by this substantially more clear-headed post by Ken Collins. The result is this crude chunk of code stuffed into my Rakefile:
Rake::Task['test:run'].clear # Intent: Kill default "rake test" task. Seems to work.
namespace :test do
task :run do
if Rails.env == "test" # Try not to obliterate other DBs.
Rake::Task["db:test:prepare"].reenable
Rake::Task["db:test:prepare"].invoke
Rake::Task["test:units"].reenable
Rake::Task["test:units"].invoke
Rake::Task["db:test:prepare"].reenable
Rake::Task["db:test:prepare"].invoke
Rake::Task["test:functionals"].reenable
Rake::Task["test:functionals"].invoke
Rake::Task["db:test:prepare"].reenable
Rake::Task["db:test:prepare"].invoke
Rake::Task["test:integration"].reenable
Rake::Task["test:integration"].invoke
end
end
end
What results from the above seems to be exactly the same as if I were to run the vanilla rake test - The suites run in order but the database does not reset as I intended, resulting in the same weird breakages each time.
But I know that it's my custom task running, because having puts statements in the block results in the statements printing to my screen BEFORE any of the test suites are run.
In other words, it looks like rake is running all my invoked tasks AFTER the chunk of code defined in my :run
task AND not running those invoked tasks more than once, which is a serious problem when the success of my suites relies on some of those tasks being able to run more than once and in the order I specify.
To be perfectly honest, I don't even know what I don't know about Rake to make it do what I want to do in this situation. If you have any guidance to offer I'd be major grateful.
Ruby submit_tag button not doing anything
I want to create a form_tag
in my index
view to accept an id
which gets passed to my populateOne
method. The view has been updated properly, both the number_field_tag
in the form and the submit_tag
are there, but when I press the button on my server, nothing happens!
Here is my view:
<%= form_tag('/affinities/populateOne/1', method: :put) %>
<%= number_field_tag(1) %>
<%= submit_tag 'Populate One' %><br>
Here are my routes:
get 'affinities/populateOne/:id' => 'affinities#populateOne', :as => 'populateOne_affinity'
My populateOne
method is long, so here is the relevant part:
def populateOne
userA = User.find(params[:id])
...
end
What could be the problem? All help is very much appreciated! Thanks!!!
Rails Constants using Initializers
I'm not sure what I'm doing wrong. I am written a module in a file: config/initalizers/constants.rb
I have a defined a module with a constant and a static method. It's accessible when called in a view. The problem occurs when I want to call the method from in one of the environment files where I get an unitialized constant error. I believe the initializers are being run after the environment files are being loaded but I am not sure where best to place the method or file.
Any help would be appreciated.
Sending information from view into controller rails
I'm stacked. Here's my form view for events :
<%= form_for(@event) do |f| %>
<div class="form-group">
<%= f.radio_button :repeat, 'once', checked: true%><br>
<%= f.label :repeat_once, 'once'%><br>
<%= f.radio_button :repeat, 'daily'%><br>
<%=f.label :repeat_daily, 'daily'%><br>
<%= f.radio_button :repeat, 'weekly'%><br>
<%= f.label :repeat_weekly, 'weekly'%><br>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And i have method in controller
def create
@event = Event.new(event_params)
@event.user_id = current_user.id
@event.save
if @event.repeat = 'daily'
////
end
if @event.repeat = 'weekly'
//////////
end
redirect_to events_url
//// it's doesn't matter what inside if block
Also my migration:
def change
add_column :events, :repeat , :string
end
The problem is in if block, because ALL OF THEM true every time regardless of my choice in view(for example i choose weekly, but anyway app makes it once and daily ) What wrong with code? Thanks for reading :) Waiting for any idea
Too many information with awesome print
I use "awesome_print" and when i do the command i have the following result :
irb(main):002:0> ap User.find(1)
←[1m←[36mUser Load (0.0ms)←[0m ←[1mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1←[0m [["id", 1]]
#<User:0x57d9650> {
:id←[0;37m => ←[0m←[1;34m1←[0m,
:name←[0;37m => ←[0m←[0;33m"aa"←[0m,
:email←[0;37m => ←[0m←[0;33m"aa"←[0m,
:created_at←[0;37m => ←[0m←[0;32mTue, 26 May 2015 15:13:51 UTC +00:00←[0m,
:updated_at←[0;37m => ←[0m←[0;32mTue, 26 May 2015 15:13:51 UTC +00:00←[0m
But i have some informations like ←[0;37m
. I have two question :
- What does that mean?
-
How do you delete them in order to print whithout this things like :
:id => 1, :first_name => "aa", :last_name => "aa" :created_at => Tue, 26 May 2015 15:13:51 UTC +00:00
Thank you in advance.
How i can call a passed argument to method in ruby
I want to pass an array object and return it to the caller function.
eg
1.rb
require '2'
class A
x=B.new
var = x.func
puts x
end
2.rb
class B
def self.func
#here i have to return same object that is x to var.what to so
end
How to manage multiple roles using polymorphic association in rails?
I am using devise for authentication and finding a way to get out of this.
class User < ActiveRecord
belongs_to :loginable, polymorphic: true
end
class Parent < ActiveRecord
has_one :user, as: :loginable
end
class Teacher < ActiveRecord
has_one :user, as: :loginable
end
Can I explore same design having user multiple roles ?. So that he can login as Teacher and Parent both?
mercredi 27 mai 2015
Rails + Devise: Creating An Additional User Account Through UI
I have a model setup that allows me to create additional accounts related to the currently logged-in Devise user.
extra_customer_account.rb:
class ExtraCustomerAccount < ActiveRecord::Base
attr_accessible :email, :customer_id, :first_name, :last_name, :password, :password_confirmation
belongs_to :customer, :foreign_key => :customer_id
validates :customer_id, :first_name, :last_name, :email, :presence => true
def self.create_with_user(email, password, first_name, last_name, customer_id)
e = ExtraCustomerAccount.create!(email: email, first_name: first_name, last_name: last_name, customer_id: customer_id)
User.create!(first_name: e.first_name, last_name: e.last_name, email: e.email, password: password, password_confirmation: password)
end
end
At the moment, I am simply creating additional accounts from Terminal as follows:
$ ExtraCustomerAccount.create_with_user("email@gmail.com", "changeme123", "First_name", "Last_name", 1)
I am now wanting to allow the logged-in user to create additional accounts themselves, without me having to do it through Terminal and struggling to link up the form in the view to hit the method in the model.
If possible, I would prefer to keep the method in the model than duplicate the code in the controller.
extra_customer_accounts_controller.rb:
class ExtraCustomerAccountsController < ApplicationController
def new
end
def create
@new_customer_account = # What goes here to call the method in model?!
end
end
Here's my attempt at the view, and I'd like the parameters of first_name, last_name, email and password to the create method in my controller. I'll also need to pass through the currently logged in customer ID.
extra_customer_account/new.html.erb:
<%= form_for @new_customer_account, :url => { action: "create" }, do |f| %>
<div class="form-group">
<div class="controls">
<%= f.text_field :first_name, :class => 'form-control custom-form-control', :placeholder => 'First name' %>
</div>
</div>
<div class="form-group">
<div class="controls">
<%= f.text_field :last_name, :class => 'form-control custom-form-control', :placeholder => 'Last name' %>
</div>
</div>
<div class="form-group">
<div class="controls">
<%= f.email_field :email, :class => 'form-control custom-form-control', :placeholder => 'Email' %>
</div>
</div>
<div class="form-group">
<div class="controls">
<%= f.password_field :password, :class => 'form-control custom-form-control ', :placeholder => 'Password' %>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn-account-primary">Create Account</button>
</div>
<% end %>
Would love some further direction as to how I could tie together my view to play nicely with a stripped-down controller and hit the method in model.
Ruby get user input in Index view
I want to create a number_field
on my index
view so that way an admin can submit an id
to a method. How can I do this?
Can I simply use a form_for
on the index
view?
A Very Specific ActiveRecord Validation
I'm will try to explain my dilemma as best I can.
I have a 2 models Users and Devices
Devices has a type column. For example it can be a Tablet or a Smart Phone.
I then have another model Ownership
This model belongs to both Users and Devices so it will have entries in the table matching users to devices representing that that user owns that device.
I need to setup some validations on the Ownership model the primary ones begin.
- No device can have more than one ownership entry (simple as validating that device_id column is unique)
- A user can only have ownership of one device for each type of device available.
So how would I make a validation for this last part? I can't set the client_id table to unique because they will have multiple entries for different types of devices. But I want them to only have one row per type of device.
I hope this makes sense. Please let me know if you need more details. I would appreciate any insight!
Thanks!
Performance differences between .exists? and .where.present?
What performance differences, if any, exist between the following two options (mentioned in this answer)
Thing.where(name: "Bob").present?
which produces the SQL
SELECT COUNT(*) FROM things WHERE things.name = "Bob";
and
Thing.exists?(name: "Bob")
which produces the SQL
SELECT 1 AS one from things WHERE name ="Bob" limit 1;
As the SQL statements are different, it's theoretically possible for differences in performance to exist. But I don't know whether, assuming name
is indexed in the database, there's any practical difference. Also, is there any difference with regards to the amount of work being done in Ruby-land (such as initialization and GC).
If it makes any difference, I'm using Rails 3.2.20.
Require "open-url" load error when executing nokogiri tester
Hi I am trying to follow the RailsCast to use Nokogiri.
Just a few very basic lines in my testing script file: require 'rubygems' require 'nokogiri' require 'open-url'
url = "http://ift.tt/1ewgqvz" doc = Nokogiri::HTML(open(url)) puts doc.at_css("title").text
But when I execute it, I run into an error: /usr/local/rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/core_ext/kernel_require.rb:54:in require': cannot load such file -- open-url (LoadError) from /usr/local/rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/core_ext/kernel_require.rb:54:in
require' from nokogiri.test.rb:3:in `'
I did install open url gem following this instruction:http://ift.tt/1Ro35ne How do I fix the error message?
Prefill right date from record into a Select Field in Edit view
I have the Following field in my Form and everything work good when i load it up to enter in a new Record starting date is 2016 and goes down to 1900 witch is fine. It will save into the record correctly. but when i go to EDIT this record it loads it up with the date of 2016 every time...
I want it to show whatever date has been saved to the database.
<%= f.select :year, options_for_select((1900..Date.today.year+1).to_a.reverse), {:prompt => 'Year', :class=>"pointer" } %>
Also this is in a nested Form and there could be several vehicles so cant just use the record instance variable.
it is nested like this:
<%= f.fields_for :vehicles do |builder| %>
<%= render "shipments/partials/vehicle_fields", :f => builder %>
<% end %>
All other fields work fine...
vehicle_fields:
<section style="margin-bottom: 0;" class="auto-container fields">
<div class="row">
<div class="col col-md-2">
<label class="select">
<%= f.select :year, options_for_select((1900..Date.today.year+1).to_a.reverse), {:prompt => 'Year', :class=>"pointer" } %>
</label>
</div>
<div class="col col-md-4">
<label class="input">
<%= f.text_field :make, :placeholder => "Make" %>
</label>
</div>
<div class="col col-md-4">
<label class="input">
<%= f.text_field :model, :placeholder => "Model" %>
</label>
</div>
<div class="col col-md-2">
<p class="btn btn-primary pull-right" style="margin: 0 0 0 20px"><%= button_to_remove_fields "Remove", f %></p>
</div>
</div>
</section>
How to load css in public files
On my project i have following routes (routes.rb)
resources :main, path: '/' do
collection do
get 'about'
get 'blog'
get 'resources'
get 'contact'
get 'projects-and-tutorials'
end
end
and these routes are loading files from public folder like about.html and contact.html, right now no css file is loaded on these pages.
I have created a css folder under public folder and will load css file from there on these public pages but i am not sure if it is good to go with
should i load css files from app/assets/stylesheets or there is another way to load css on public files ?
mardi 26 mai 2015
Rails: NoMethodError, how do I show users profiles?
When I type at the top, /users/1
or /users/2
I get the same page yet there are 2 users. It just redirects me back to show.html.rb page. I'm not sure but maybe I don't have a page for each user. Maybe you can look at my code. I am unable to show <%= @user.name %>
, I get a NoMethodError in Users#show
. Maybe that is the problem...
show.html.rb
Avatar, <%= image_tag(current_user.avatar.url(:medium)) %>
Hello, <%= current_user.name %>
routes.rb
Rails.application.routes.draw do
resources :products
get 'users/index'
get 'users/show'
devise_for :users do
resources :posts
end
get 'users/:id' => 'users#show', as: :user
resources :posts do
member do
get "like", to: "posts#upvote"
get "dislike", to: "posts#downvote"
end
resources :comments
end
root 'posts#index'
end
I have each user in Show.html.rb and an index showing all the users at Index.html.rb
users_controller.rb
class UsersController < ApplicationController
before_action :authenticate_user!
def index
@users = User.all
end
def edit
@user = User.create( user_params )
end
def show
@user = User.find_by_name(params[:id])
@product = current_user.products.where(availability: true)
@purchased = Sale.where(buyer_email: current_user.email)
@sales = Sale.where(seller_email: current_user.email)
@products = current_user.products
end
private
def user_params
params.require(:user).permit(:name, :email, :avatar)
end
end
Why Rails instance method can be used as class method in rspec
I found a snippet in an article about sending mails in a Rails application:
class ExampleMailerPreview < ActionMailer::Preview
def sample_mail_preview
ExampleMailer.sample_email(User.first)
end
end
in this link: http://ift.tt/11PqLfz.
I do not know why the method: sample_email()
, which in my mind should be an instance method, can be accessed like class method here as ExampleMailer.sample_email()
. Can anyone explain?
Form data not being sent in the email
Below is code that I have that I basically just mimicked. A professional web developer made the website, so im just following how they did it. But, for some reason the data does not get sent in the email. But, the email does send.
controller file
def createproject
@title = "Create Your Project"
@txtname = params[:txtname]
@txtemail = params[:txtemail]
@txtdates = params[:txtdates]
@tname = params[:tname]
@txtleader = params[:txtleader]
@txttree = params[:txttree]
@txtsolar = params[:txtsolar]
@txtwater = params[:txtwater]
@txtgoats = params[:txtgoats]
@txtkids = params[:txtkids]
@txthouse = params[:txthouse]
@txtroof = params[:txtroof]
@txtlatrine = params[:txtlatrine]
@txtbuild = params[:txtbuild]
if !@txtname.nil? && @txtname != ''
@isvalid = true
@data = {
:txtname => @txtname,
:txtemail => @txtemail,
:txtdates => @txtdates,
:tname => @tname,
:txtleader => @txtleader,
:txttree => @txttree,
:txtsolar => @txtsolar,
:txtwater => @txtwater,
:txtgoats => @txtgoats,
:txtkids => @txtkids,
:txthouse => @txthouse,
:txtroof => @txtroof,
:txtlatrine => @txtlatrine,
:txtbuild => @txtbuild
}
end
if @isvalid
ContactUsMailer.createproject_mail(@data).deliver
respond_to do |format|
format.html {render :layout=>"homeLayout"}
end
else
respond_to do |format|
format.html {render :layout=>"homeLayout"}
end
end
end
mailer file
def createproject_mail(data)
@data = data
@txtname = @data[:txtname]
@txtemail = @data[:txtemail]
@txtdates = @data[:txtdates]
@tname = @data[:tname]
@txtleader = @data[:txtleader]
@txttree = @data[:txttree]
@txtsolar = @data[:txtsolar]
@txtwater = @data[:txtwater]
@txtgoats = @data[:txtgoats]
@txtkids = @data[:txtkids]
@txthouse = @data[:txthouse]
@txtroof = @data[:txtroof]
@txtlatrine = @data[:txtlatrine]
@txtbuild = @data[:txtbuild]
mail(:to => "jacob@fusionbible.com", :subject => "TEST", :from => "no-reply@mohhaiti.org")
end
Ruby Geocoder, resulting in Nil values for Latitude & Longitude columns
I have a simple Rails 3 app that uses Ruby Geocoder for a search form that my end users can use to determine their distance from other users of my app. I followed RailsCast episode #273 to implement it. However, sometimes when a new user is building his/her profile (which requires that they enter their zip code), the latitude & longitude columns of their record end up nil. In other words, their record is not being "geocoded." It seems to be pretty rare, but I'd like to determine a way to prevent this. Thanks!
Profile Model
class Profile < ActiveRecord::Base
attr_accessible :zip_code, :latitude, :longitude
geocoded_by :zip_code
after_validation :geocode, :if => :zip_code_changed?
VALID_ZIP_CODE_REGEX = /^\d{5}$/
validates :zip_code, presence: true, format: { with: VALID_ZIP_CODE_REGEX } # accepts 5-digit zip codes only
end
Rails, be a pal and reset the database between test suites
Work is transitioning from Rails 3 to Rails 4. Everything seems to be running more or less smoothly on the development side, but testing results in a multitude of varying failures when all suites - units, functionals, and integration - are run in one go with rake:test
.
What's interesting is that running each of these suites individually produces no failures. This strongly suggests that the database is not resetting for our tests in Rails 4 quite the way it was in Rails 3.
I've tried overriding the rake:test task to execute db:test:prepare
prior to running each suite, but this apparently doesn't do what I think it does, or rather, what I want it to do, which is to work with a fresh set of data for each test and therefore succeed or fail independently of every other test - the way it (was or should have been) in our Rails 3 setup.
Why is this happening? How might I fix it?
(Note that the testing framework is vanilla Rails with fixtures and the like. The testing failures we're getting are usually foreign key errors or failures for data to change in expected ways that don't show up when the DB is reset before a testing suite.)
User can't delete his own account , Rails 4 + Devise
I have Ruby on Rails 4 application also I am using Devise gem to provide login/register.
Everything works just fine, but users that are logged in can't delete their own account. Any other delete functions work, so Javascript shouldn't be a problem.
In view:
<%= link_to "Delete account", registration_path(resource_name), data: { confirm: "Your profile will be permanently deleted. Are you sure?" }, method: :delete%>
I am overriding default devise Registration controller with this:
class RegistrationsController < Devise::RegistrationsController
clear_respond_to
respond_to :json
protected
def update_resource(resource, params)
resource.update_without_password(params)
end
end
My log file:
Started DELETE "/ru/users" for xx.xxx.xxxx.xx at 2015-05-26 22:30:45 +0300
Processing by RegistrationsController#destroy as HTML
Parameters: {"authenticity_token"=>"dXKjMMmKibIy2LNCrR66JuThjPzqsdtjFMXTCubcFe8=", "locale"=>"ru"}
[1m[36mUser Load (0.3ms)[0m [1mSELECT `users`.* FROM `users` WHERE `users`.`id` = 66 ORDER BY `users`.`id` ASC LIMIT 1[0m
[1m[35mCountry Load (0.3ms)[0m SELECT `countries`.* FROM `countries` WHERE `countries`.`id` = 1 LIMIT 1
[1m[36m (0.6ms)[0m [1mSELECT COUNT(*) FROM `girls` WHERE (country_id=1) AND (vip_recomend >= '2015-05-26 22:30:45')[0m
[1m[35m (0.4ms)[0m SELECT COUNT(*) FROM `girls` WHERE (country_id=1) AND (recomend >= '2015-05-26 22:30:45')
[1m[36m (0.3ms)[0m [1mSELECT COUNT(*) FROM `girls` WHERE (country_id=1) AND (highlight >= '2015-05-26 22:30:45')[0m
[1m[35m (0.3ms)[0m SELECT COUNT(*) FROM `girls` WHERE (country_id=1) AND (vip_highlight >= '2015-05-26 22:30:45')
[1m[36mRegion Load (0.2ms)[0m [1mSELECT `regions`.* FROM `regions` WHERE `regions`.`country_id` = 1[0m
[1m[35mList Load (0.3ms)[0m SELECT `lists`.* FROM `lists` WHERE (billing_id =5) ORDER BY `lists`.`id` ASC LIMIT 1
[1m[36m (0.3ms)[0m [1mBEGIN[0m
[1m[35m (0.2ms)[0m COMMIT
[1m[36m (0.2ms)[0m [1mBEGIN[0m
[1m[35m (0.2ms)[0m COMMIT
Redirected to http://ift.tt/1AseAWL
Completed 302 Found in 24ms (ActiveRecord: 4.4ms)
Description:
When user pushes delete button, user gets message :
translation missing: ru.devise.registrations.user.destroyed
also he is logged out from his account, but the actual destroying never happens. What could be possible problem?
Thanks for your time. Best wishes.
Rails can't find installed gem
I'm following a tutorial for Rails that specifically asks for version 4.2.0
so I installed Rails with sudo gem install rails -v 4.2.0
and it worked fine. When I try to create a new application with rails _4.2.0 new test_app
I get an error message that says /Library/Ruby/Site/2.0.0/rubygems/dependency.rb.315: in 'to_specs': Could not find 'railties' (=4.2.0) - did find: [railties-4.2.1] (Gem::LoadError)
and continues on for a little bit more.
I've tried installing that specific version of railties
with sudo gem install railties -v 4.2.0
but I still get the same error. Is it checking for/installing the gem in two different places?
EDIT: Running gem list
yields the following output, clearly showing railties (4.2.0)
:
*** LOCAL GEMS ***
actionmailer (4.2.0)
actionpack (4.2.1, 4.2.0)
actionview (4.2.1, 4.2.0)
activejob (4.2.1, 4.2.0)
activemodel (4.2.0)
activerecord (4.2.0)
activesupport (4.2.1, 4.2.0)
arel (6.0.0)
bigdecimal (1.2.6)
builder (3.2.2)
bundler (1.9.9)
erubis (2.7.0)
globalid (0.3.5)
i18n (0.7.0)
io-console (0.4.3)
json (1.8.2, 1.8.1)
loofah (2.0.2)
mail (2.6.3)
mime-types (2.6.1)
mini_portile (0.6.2)
minitest (5.6.1, 5.4.3)
nokogiri (1.6.6.2)
power_assert (0.2.2)
psych (2.0.8)
rack (1.6.1)
rack-test (0.6.3)
rails (4.2.0)
rails-deprecated_sanitizer (1.0.3)
rails-dom-testing (1.0.6)
rails-html-sanitizer (1.0.2)
railties (4.2.0)
rake (10.4.2)
rdoc (4.2.0)
sprockets (3.1.0)
sprockets-rails (2.3.1)
test-unit (3.0.8)
thor (0.19.1)
thread_safe (0.3.5)
tzinfo (1.2.2)
How to reduce eager_load query overhead (ActiveRecord)?
I have the following model:
# address.rb
class Address < ActiveRecord::Base
has_many :orders_for_cleaning, class_name: 'Order',
foreign_key: :cleaning_address_id
has_many :orders_for_billing, class_name: 'Order',
foreign_key: :billing_address_id
has_many :purchases_for_shipping, class_name: 'Purchase',
foreign_key: :shipping_address_id
has_many :purchases_for_billing, class_name: 'Purchase',
foreign_key: :billing_address_id
end
and I want to fetch all addresses of a certain Customer
through his orders
a purchases
using eager_load
:
# customer.rb
def addresses
Address.eager_load(:orders_for_cleaning,
:orders_for_billing,
:purchases_for_shipping,
:purchases_for_billing)
.where('orders.customer_id = ?
OR orders_for_billings_addresses.customer_id = ?
OR purchases.customer_id = ?
OR purchases_for_billings_addresses.customer_id = ?',
id, id, id, id)
end
This request generates the following query:
SELECT DISTINCT "addresses"."id" AS t0_r0,
"addresses"."latitude" AS t0_r1,
"addresses"."longitude" AS t0_r2,
"addresses"."house" AS t0_r3,
"addresses"."street" AS t0_r4,
"addresses"."city" AS t0_r5,
"addresses"."zip" AS t0_r6,
"addresses"."state" AS t0_r7,
"addresses"."country" AS t0_r8,
"addresses"."created_at" AS t0_r9,
"addresses"."updated_at" AS t0_r10,
"addresses"."street2" AS t0_r11,
"addresses"."custom_latitude" AS t0_r12,
"addresses"."custom_longitude" AS t0_r13,
"addresses"."name" AS t0_r14,
"addresses"."company" AS t0_r15,
"addresses"."archived" AS t0_r16,
"orders"."id" AS t1_r0,
"orders"."customer_id" AS t1_r1,
"orders"."cleaning_address_id" AS t1_r2,
"orders"."billing_address_id" AS t1_r3,
"orders"."start_at" AS t1_r4,
"orders"."finish_at" AS t1_r5,
"orders"."planned_at" AS t1_r6,
"orders"."started_at" AS t1_r7,
"orders"."finished_at" AS t1_r8,
"orders"."payed_price" AS t1_r9,
"orders"."status" AS t1_r10,
"orders"."pin" AS t1_r11,
"orders"."comment" AS t1_r12,
"orders"."created_at" AS t1_r13,
"orders"."updated_at" AS t1_r14,
"orders"."name" AS t1_r15,
"orders"."company" AS t1_r16,
"orders"."phone" AS t1_r17,
"orders"."coupon_code" AS t1_r18,
"orders"."coupon_discount" AS t1_r19,
"orders"."location_id" AS t1_r20,
"orders"."location_discount" AS t1_r21,
"orders"."job_count" AS t1_r22,
"orders"."bonus" AS t1_r23,
"orders"."organization_id" AS t1_r24,
"orders"."bill_id" AS t1_r25,
"orders"."cleaning_count_discount" AS t1_r26,
"orders"."created_by" AS t1_r27,
"orders"."price_group_id" AS t1_r28,
"orders"."travel_charge" AS t1_r29,
"orders"."departed_at" AS t1_r30,
"orders"."arrived_at" AS t1_r31,
"orders"."request_feedback" AS t1_r32,
"orders"."feedback_link" AS t1_r33,
"orders"."feedback_requested_at" AS t1_r34,
"orders"."rating" AS t1_r35,
"orders"."feedback" AS t1_r36,
"orders"."profit_center_code" AS t1_r37,
"orders"."feedback_received_at" AS t1_r38,
"orders"."reorder_bonus" AS t1_r39,
"orders"."paid_to" AS t1_r40,
"orders"."cleaner_id" AS t1_r41,
"orders"."station_id" AS t1_r42,
"orders"."cleaner_comment" AS t1_r43,
"orders_for_billings_addresses"."id" AS t2_r0,
"orders_for_billings_addresses"."customer_id" AS t2_r1,
"orders_for_billings_addresses"."cleaning_address_id" AS t2_r2,
"orders_for_billings_addresses"."billing_address_id" AS t2_r3,
"orders_for_billings_addresses"."start_at" AS t2_r4,
"orders_for_billings_addresses"."finish_at" AS t2_r5,
"orders_for_billings_addresses"."planned_at" AS t2_r6,
"orders_for_billings_addresses"."started_at" AS t2_r7,
"orders_for_billings_addresses"."finished_at" AS t2_r8,
"orders_for_billings_addresses"."payed_price" AS t2_r9,
"orders_for_billings_addresses"."status" AS t2_r10,
"orders_for_billings_addresses"."pin" AS t2_r11,
"orders_for_billings_addresses"."comment" AS t2_r12,
"orders_for_billings_addresses"."created_at" AS t2_r13,
"orders_for_billings_addresses"."updated_at" AS t2_r14,
"orders_for_billings_addresses"."name" AS t2_r15,
"orders_for_billings_addresses"."company" AS t2_r16,
"orders_for_billings_addresses"."phone" AS t2_r17,
"orders_for_billings_addresses"."coupon_code" AS t2_r18,
"orders_for_billings_addresses"."coupon_discount" AS t2_r19,
"orders_for_billings_addresses"."location_id" AS t2_r20,
"orders_for_billings_addresses"."location_discount" AS t2_r21,
"orders_for_billings_addresses"."job_count" AS t2_r22,
"orders_for_billings_addresses"."bonus" AS t2_r23,
"orders_for_billings_addresses"."organization_id" AS t2_r24,
"orders_for_billings_addresses"."bill_id" AS t2_r25,
"orders_for_billings_addresses"."cleaning_count_discount" AS t2_r26,
"orders_for_billings_addresses"."created_by" AS t2_r27,
"orders_for_billings_addresses"."price_group_id" AS t2_r28,
"orders_for_billings_addresses"."travel_charge" AS t2_r29,
"orders_for_billings_addresses"."departed_at" AS t2_r30,
"orders_for_billings_addresses"."arrived_at" AS t2_r31,
"orders_for_billings_addresses"."request_feedback" AS t2_r32,
"orders_for_billings_addresses"."feedback_link" AS t2_r33,
"orders_for_billings_addresses"."feedback_requested_at" AS t2_r34,
"orders_for_billings_addresses"."rating" AS t2_r35,
"orders_for_billings_addresses"."feedback" AS t2_r36,
"orders_for_billings_addresses"."profit_center_code" AS t2_r37,
"orders_for_billings_addresses"."feedback_received_at" AS t2_r38,
"orders_for_billings_addresses"."reorder_bonus" AS t2_r39,
"orders_for_billings_addresses"."paid_to" AS t2_r40,
"orders_for_billings_addresses"."cleaner_id" AS t2_r41,
"orders_for_billings_addresses"."station_id" AS t2_r42,
"orders_for_billings_addresses"."cleaner_comment" AS t2_r43,
"purchases"."id" AS t3_r0,
"purchases"."product_price_group_id" AS t3_r1,
"purchases"."customer_id" AS t3_r2,
"purchases"."shipping_address_id" AS t3_r3,
"purchases"."billing_address_id" AS t3_r4,
"purchases"."created_by" AS t3_r5,
"purchases"."token" AS t3_r6,
"purchases"."shipping" AS t3_r7,
"purchases"."coupon_code" AS t3_r8,
"purchases"."coupon_discount" AS t3_r9,
"purchases"."comment" AS t3_r10,
"purchases"."status" AS t3_r11,
"purchases"."purchased_at" AS t3_r12,
"purchases"."created_at" AS t3_r13,
"purchases"."updated_at" AS t3_r14,
"purchases"."purchase_invoice_id" AS t3_r15,
"purchases"."payment" AS t3_r16,
"purchases"."pickup" AS t3_r17,
"purchases"."tracking_number" AS t3_r18,
"purchases"."paper_invoice_sent_at" AS t3_r19,
"purchases_for_billings_addresses"."id" AS t4_r0,
"purchases_for_billings_addresses"."product_price_group_id" AS t4_r1,
"purchases_for_billings_addresses"."customer_id" AS t4_r2,
"purchases_for_billings_addresses"."shipping_address_id" AS t4_r3,
"purchases_for_billings_addresses"."billing_address_id" AS t4_r4,
"purchases_for_billings_addresses"."created_by" AS t4_r5,
"purchases_for_billings_addresses"."token" AS t4_r6,
"purchases_for_billings_addresses"."shipping" AS t4_r7,
"purchases_for_billings_addresses"."coupon_code" AS t4_r8,
"purchases_for_billings_addresses"."coupon_discount" AS t4_r9,
"purchases_for_billings_addresses"."comment" AS t4_r10,
"purchases_for_billings_addresses"."status" AS t4_r11,
"purchases_for_billings_addresses"."purchased_at" AS t4_r12,
"purchases_for_billings_addresses"."created_at" AS t4_r13,
"purchases_for_billings_addresses"."updated_at" AS t4_r14,
"purchases_for_billings_addresses"."purchase_invoice_id" AS t4_r15,
"purchases_for_billings_addresses"."payment" AS t4_r16,
"purchases_for_billings_addresses"."pickup" AS t4_r17,
"purchases_for_billings_addresses"."tracking_number" AS t4_r18,
"purchases_for_billings_addresses"."paper_invoice_sent_at" AS t4_r19
FROM "addresses"
LEFT OUTER JOIN "orders"
ON "orders"."cleaning_address_id" = "addresses"."id"
LEFT OUTER JOIN "orders" "orders_for_billings_addresses"
ON "orders_for_billings_addresses"."billing_address_id" = "addresses"."id"
LEFT OUTER JOIN "purchases"
ON "purchases"."shipping_address_id" = "addresses"."id"
LEFT OUTER JOIN "purchases" "purchases_for_billings_addresses"
ON "purchases_for_billings_addresses"."billing_address_id" = "addresses"."id"
WHERE (orders.customer_id = 3282 OR orders_for_billings_addresses.customer_id = 3282
OR purchases.customer_id = 3282 OR purchases_for_billings_addresses.customer_id = 3282)
this query takes about 100ms on my dataset.
But I don't need to load all join model columns just their foreign keys. If I execute stripped SQL query:
SELECT addresses.*,
orders.cleaning_address_id,
orders_for_billings_addresses.billing_address_id,
purchases.shipping_address_id,
purchases_for_billings_addresses.billing_address_id
FROM addresses
LEFT OUTER JOIN orders
ON orders.cleaning_address_id = addresses.id
LEFT OUTER JOIN orders orders_for_billings_addresses
ON orders_for_billings_addresses.billing_address_id = addresses.id
LEFT OUTER JOIN purchases
ON purchases.shipping_address_id = addresses.id
LEFT OUTER JOIN purchases purchases_for_billings_addresses
ON purchases_for_billings_addresses.billing_address_id = addresses.id
WHERE (orders.customer_id = 3282
OR orders_for_billings_addresses.customer_id = 3282
OR purchases.customer_id = 3282
OR purchases_for_billings_addresses.customer_id = 3282)
It returns the same results in only 50ms.
The question: is there a way to enforce ActiveRecord
to select only necessary fields with eager_load
? Adding select('addresses.*, <fk_fields...>)
doesn't help.
Unicorn+Nginx concurrency and data corruption
I have 4 Nginx workers and 4 unicorn workers. We hit a concurrency issue in some of our models that validate unique names. We are getting duplicated names when we send multiple requests at the same time on the same resource.
Here's some context
Model (simplify)
class License < ActiveRecord::Base
validates :serial_number, :uniqueness => true
end
Unicorn.rb
APP_PATH = '.../manager'
worker_processes 4
working_directory APP_PATH # available in 0.94.0+
listen ".../manager/tmp/sockets/manager_rails.sock", backlog: 1024
listen 8080, :tcp_nopush => true # uncomment to listen to TCP port as well
timeout 600
pid "#{APP_PATH}/tmp/pids/unicorn.pid"
stderr_path "#{APP_PATH}/log/unicorn.stderr.log"
stdout_path "#{APP_PATH}/log/unicorn.stdout.log"
preload_app true
GC.copy_on_write_friendly = true if GC.respond_to?(:copy_on_write_friendly=)
check_client_connection false
run_once = true
before_fork do |server, worker|
ActiveRecord::Base.connection.disconnect! if defined?(ActiveRecord::Base)
MESSAGE_QUEUE.close
end
after_fork do |server, worker|
ActiveRecord::Base.establish_connection if defined?(ActiveRecord::Base)
end
Nginx.conf (simplify)
worker_processes 4;
events {
multi_accept off;
worker_connections 1024;
use epoll;
accept_mutex off;
}
upstream app_server {
server unix:/home/blueserver/symphony/manager/tmp/sockets/manager_rails_write.sock fail_timeout=0;
}
try_files $uri @app;
location @app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
proxy_pass http://app_server;
}
Every time I send multiple requests (around 10+) to create Licenses I get some duplicates. I understand why. It's because each unicorn process doesn't have a resource with the serial_number created yet and it might create it multiple times...
ActiveRecord is validating the uniqueness of the field at the application level rather than a database level. One workaround could be moving the validations to the database (but it will be very cumbersome)
Another workaround is to limit the write requests (POST/PUT/DELETE) to only one unicorn and have multiple unicorns to reply to read requests (GET)... Something like this in the location in Nginx...
# 4 unicorn workers for GET requests
proxy_pass http://app_read_server;
# 1 unicorn worker for POST/PUT/DELETE requests
limit_except GET {
proxy_pass http://app_write_server;
}
This fixes the concurrency issue. However, one write server is not enough to reply at peak times.
Any idea to solve the concurrency and scalability issues with Nginx+Unicorn?
Is there any way to print a database content in a pretty syntax?
I have a simple database in ruby on rail and i want to know if there is a way to display properly the result of a request in ruby.
For example in a base which is like this : User(id, name, email) whith a content like that :
(1, jack, j@j.com);(2, jhon, jo@jo.com); (3, janet, j@j.com)
I do rails console
then User.where(email: "j@j.com")
It return two line but it's not correctly formated to be lisible. Do you know some command in order to well format the output when you have multiple line.
Thank you in advance.
RoR SanitizeHelper Allow script tag content
I have constructed a whitelist of all the tags I want to allow when sanitizing a document which includes script tags and used ActionView::Helpers::SanitizeHelper to help with the sanitizing. My problem is that the script tag is allowed to display in the HTML source but the contents of the script are removed.
I can display without the sanitizing for this specific section of my application but would prefer to keep everything consistent.
This is my line code for that sanitizing section
#{sanitize @page.body, tags: t("sanitize.whitelist").split(/\s/), attributes: %w(id class style alt src href target)}
Any help would be appreciated before I just have to resolve to removing sanitizing on this section.
Sorting a Rails active record
I have a table A(:name, :address, :country_id)
. I run this query
ids = [1,2,3]
A.where(country_id: ids)
But, I want to get the results in this order : records containing country_id = 2 first, then 1 and then 3
.
How should I write this query?
How to add associations to models in rails
I have three models
class SupplierVariant
belongs_to :supplier
belongs_to :variant
end
class Supplier
has_many :variants, :through :supplier_variants
end
class Variant
end
Now I want to know, how to get supplier of a particular variant.I added an association has_one :supplier through: :supplier_variant
in Variant class
but when I do the following query I get below mentioned error
p=Spree::Variant.find(384)
Spree::Variant Load (1.2ms) SELECT "spree_variants".* FROM "spree_variants" WHERE "spree_variants"."deleted_at" IS NULL AND "spree_variants"."id" = ? LIMIT 1 [["id", 384]]
=> #<Spree::Variant id: 384, sku: "CHG137-Blue-XL", weight: #<BigDecimal:a396b38,'0.5E3',9(27)>, height: #<BigDecimal:a396a20,'0.5E2',9(27)>, width: #<BigDecimal:a3968e0,'0.45E2',9(27)>, depth: #<BigDecimal:a396778,'0.75E2',9(27)>, deleted_at: nil, is_master: false, product_id: 228, cost_price: #<BigDecimal:a3962c8,'0.9E3',9(27)>, position: 4, cost_currency: "INR", track_inventory: true, tax_category_id: 3, updated_at: "2015-05-25 05:58:19", stock_items_count: 4>
p.supplier
**NoMethodError: undefined method `supplier' for #<Spree::Variant:0x0000000a3973a8>**
How to add proper associations in model folder in rails? and How to use them after we add it? Does applying join operation between tables depend on the associations we define in models?
lundi 25 mai 2015
Update a table in rails
I have a table A(:name, :address, :phone)
and want to update the names and addresses of all the records. The following lines of code helps me doing it but takes a lot of time :
A.find_each(batch_size: 10000) do |a|
new_name = "xyz"
new_address = "abc"
A.find(a.id).update(name: name, address: new_address)
end
It takes times because of the last line as I am finding the record first, then updating it. Now when I do this :
A.find_each(batch_size: 10000) do |a|
a.name = "xyz"
a.address = "abc"
a.save
end
The names and addresses don't get updated in this case but a.save returns true. What could be wrong?
When I try to run "rails s" or "rails server" command I get an error and It does not let me start the server
Once I install rails then I got into a folder and type in rails new app
. Then I go into the folder and run bundle install
. Once I have installed all the necessary gems I go into the applications folder and i type in either
rails s
or
rails server
and I get the following error:
C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.6.2-x64-mingw32/lib/nokogiri
.rb:29:in `require': cannot load such file -- nokogiri/nokogiri (LoadError)
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.6.2-x64-mingw32
/lib/nokogiri.rb:29:in `rescue in <top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.6.2-x64-mingw32
/lib/nokogiri.rb:25:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/loofah-2.0.2/lib/loofah.rb:3
:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/loofah-2.0.2/lib/loofah.rb:3
:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rails-html-sanitizer-1.0.2/l
ib/rails-html-sanitizer.rb:2:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rails-html-sanitizer-1.0.2/l
ib/rails-html-sanitizer.rb:2:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.1/lib/action_
view/helpers/sanitize_helper.rb:3:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.1/lib/action_
view/helpers/sanitize_helper.rb:3:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.1/lib/action_
view/helpers/text_helper.rb:32:in `<module:TextHelper>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.1/lib/action_
view/helpers/text_helper.rb:29:in `<module:Helpers>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.1/lib/action_
view/helpers/text_helper.rb:6:in `<module:ActionView>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.1/lib/action_
view/helpers/text_helper.rb:4:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.1/lib/action_
view/helpers/form_tag_helper.rb:18:in `<module:FormTagHelper>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.1/lib/action_
view/helpers/form_tag_helper.rb:14:in `<module:Helpers>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.1/lib/action_
view/helpers/form_tag_helper.rb:8:in `<module:ActionView>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.1/lib/action_
view/helpers/form_tag_helper.rb:6:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.1/lib/action_
view/helpers/form_helper.rb:4:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.1/lib/action_
view/helpers/form_helper.rb:4:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.1/lib/action_
view/helpers.rb:50:in `<module:Helpers>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.1/lib/action_
view/helpers.rb:4:in `<module:ActionView>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.1/lib/action_
view/helpers.rb:3:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.0/lib/sp
rockets/rails/legacy_asset_tag_helper.rb:7:in `<module:LegacyAssetTagHelper>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.0/lib/sp
rockets/rails/legacy_asset_tag_helper.rb:6:in `<module:Rails>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.0/lib/sp
rockets/rails/legacy_asset_tag_helper.rb:4:in `<module:Sprockets>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.0/lib/sp
rockets/rails/legacy_asset_tag_helper.rb:3:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.0/lib/sp
rockets/rails/helper.rb:54:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.0/lib/sp
rockets/rails/helper.rb:54:in `<module:Helper>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.0/lib/sp
rockets/rails/helper.rb:7:in `<module:Rails>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.0/lib/sp
rockets/rails/helper.rb:6:in `<module:Sprockets>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.0/lib/sp
rockets/rails/helper.rb:5:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.0/lib/sp
rockets/railtie.rb:6:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.0/lib/sp
rockets/railtie.rb:6:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass/ra
ils/railtie.rb:3:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass/ra
ils/railtie.rb:3:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass/ra
ils.rb:11:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass/ra
ils.rb:11:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass-ra
ils.rb:1:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass-ra
ils.rb:1:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.9.6/lib/bundler/ru
ntime.rb:76:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.9.6/lib/bundler/ru
ntime.rb:76:in `block (2 levels) in require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.9.6/lib/bundler/ru
ntime.rb:72:in `each'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.9.6/lib/bundler/ru
ntime.rb:72:in `block in require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.9.6/lib/bundler/ru
ntime.rb:61:in `each'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.9.6/lib/bundler/ru
ntime.rb:61:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.9.6/lib/bundler.rb
:134:in `require'
from C:/RubyProjects/app/config/application.rb:7:in `<top (required)>'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/com
mands/commands_tasks.rb:78:in `require'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/com
mands/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/com
mands/commands_tasks.rb:75:in `tap'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/com
mands/commands_tasks.rb:75:in `server'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/com
mands/commands_tasks.rb:39:in `run_command!'
from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.1/lib/rails/com
mands.rb:17:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
Does anyone have any idea why this might be happening and how can I fix that?
Thank you!
ancestry gem - a way to build the tree?
I have a menu which has_many :menu_headers. I'd like to just output the tree of menu_headers. Is there a way to do this via the gem rather than iterating through all the menu_headers?
Sent emails with Action Mailer
I am trying to send an email to example@gmail.com with Action Mailer (Ruby on Rails). The method sendactivation is correctly executed and the message "Email sent" is displayed. However, I never receive any email. Actually, the output "Test" is never printed. My webapp is hosted on Heroku Cedar-10.
class UsersController < ApplicationController
def sendactivation
UserMailer.welcome_email()
render :json => {
:result => "Email sent"
}
end
end
end
class UserMailer < ActionMailer::Base
def welcome_email()
mail(to: "example@gmail.com",
body: "Hello",
content_type: "text/html",
subject: "Already rendered!")
puts "Test"
end
end
This is the configuration I have on my config/environment/production.rb. Actually I wanted to send it with Office 365 but I suppose it is easier to debug with a Gmail account.
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
user_name: 'example@gmail.com',
password: '########',
authentication: 'plain',
enable_starttls_auto: true }
What am I doing wrong? Is there anything I need to change on my Gmail configuration?
How to submit multiple fields into an Array of values
Ok i have the following form fields that i would like to submit in an array of vehicle like
car = [{:year => 2012, :make => "Ford", :model => mustang}, {:year => 2015, :make => "Chevy", :model => "S-10"}, {:year => 2014, :make => "Dodge", :model => "Caravan"}]
at the moment it is sending in this (only the last set of car)
Parameters: {"utf8"=>"✓", "authenticity_token"=>"iMyNj94iSBuV3ZL0EVHRjet6kt4EEYe6Ajc1XA2Cq+8=", "post"=>{"title"=>"", "category_id"=>"1", "notes"=>"", "stops"=>"", "promote"=>"0", "user_id"=>"1"}, "car"=>{"year"=>"2016", "make"=>"", "model"=>""}, "commit"=>"Create Post"}
this is the form coding that i have
<div id="auto">
<section style="margin-bottom: 0;">
<div class="row">
<div class="col col-md-4">
<label class="select">
<select class="pointer" id="car_year" name="car[year]"><option value="2016">2016</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
</select>
</label>
</div>
<div class="col col-md-4">
<label class="input">
<input id="car_make" name="car[make]" placeholder="Make" type="text" value="">
</label>
</div>
<div class="col col-md-4">
<label class="input">
<input id="car_model" name="car[model]" placeholder="Model" type="text" value="">
</label>
</div>
</div>
</section>
<section style="margin-bottom: 0;">
<div class="row">
<div class="col col-md-4">
<label class="select">
<select class="pointer" id="car_year" name="car[year]"><option value="2016">2016</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
</select>
</label>
</div>
<div class="col col-md-4">
<label class="input">
<input id="car_make" name="car[make]" placeholder="Make" type="text" value="">
</label>
</div>
<div class="col col-md-4">
<label class="input">
<input id="car_model" name="car[model]" placeholder="Model" type="text" value="">
</label>
</div>
</div>
</section><section style="margin-bottom: 0;">
<div class="row">
<div class="col col-md-4">
<label class="select">
<select class="pointer" id="car_year" name="car[year]"><option value="2016">2016</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
</select>
</label>
</div>
<div class="col col-md-4">
<label class="input">
<input id="car_make" name="car[make]" placeholder="Make" type="text" value="">
</label>
</div>
<div class="col col-md-4">
<label class="input">
<input id="car_model" name="car[model]" placeholder="Model" type="text" value="">
</label>
</div>
</div>
</section></div>
here is my form that i add more of these fields to dynamically...
How to use join operation in rails to get desired result
I am new to Ruby-on-Rails I have following tables with below mentioned attributes
Supplier - id ,name,address etc------
Variant - id ,price,etc---
SupplierVariant- supplier_id,variant_id
LineItem - variant_id ,order_id
There is one more table called 'Order' which has line_items as it attribute.Each 'Order' object is linked to variant through lineitems.My requirement is to get all the supplier_ids from a particular order using the join operation between the tables.
I am using 'Spree' to build my application and for the above mentioned question I have tried the following in rails console
ord=Spree::Order.find_by_number("R1218823")
var=ord.line_items.joins(:variant)
till here it's working fine, but when I do var.joins(:SupplierVariant), I am getting error.
Run a rails query in batches
I have a table A(:name, :address, :phone)
consisting of 500,000 entries. I want to run this query :
johns = A.where(:name => "John")
This query should return 150,000 results. But running this query gives me this result : Killed
.
How should I rewrite this query so that the query runs on batches of 1000 in the database?
add +1 for month indexing in pickadate
i want to disable all dates excepting from range of start_date and end_date. and i am using pickadate and pickadate month indexing start from zero.
$('.datepicker2').pickadate({
format: 'dd/md/yyyy',
selectMonths: true,
selectYears: 25,
min: [$("#leave_start_date").val().split("/").map(Number).reverse()],
max: [$("#leave_end_date").val().split("/").map(Number).reverse()]
});
but it is not working. its disable all dates remaining current date. please help me . i want to disable that dates only who is not coming in range of start_date and end_date values.
Dump mysql error in rails 3.2.13
I need to dump all my data into another rails application.I can't dump a data.I tried this command to dump my mysql file
mysql -u root -p like_fb_graph_development < like_fb_graph_development.sql
I am getting this ERROR 1054 (42S22) at line 420: Unknown column 'email' in 'field list'
dimanche 24 mai 2015
Ruby on Rails: How to link/route from one view/page to another view/page with a different controller
I have a view template within the following file in my Rails application:
app/views/static_pages/mission.html.erb
I want to link to that page from a view template in a different folder (corresponding to a different page in the app):
app/views/home/home.html.erb
I don't know what to write in my mission
method in the StaticPagesController
. I'm also a newbie at Rails. I also don't know how to write the route for it and I suspect I may need to write a get 'something' in my routes.rb file.
Can anybody help with this?
Rails: Why does it show nil in the database?
Is it because of the controller, the model, or something else? If I add a column in the model, how do I populate it? Do I have to have a box where users fill in their information? How do i automatically auto fill the database when a user creates a file
Many-to-zero mongoid relation causing other model to update anyway, Devise session dropping
I have a problem with Devise giving me 401 Unauthorized after creating a new user and referencing models in a callback (I use a custom cms, based on Rails 3.2.18 and Devise 3.4.1). Here's my models:
class User
...
after_create :initialize_conversations
def initialize_conversations
user = self
User.where(category: 'admins').each do |interlocutor|
Conversation.create!(posters: [user, interlocutor])
#I am logged in as admin, so one of the instances has my account as interlocutor
end
end
end
class Conversation
...
has_and_belongs_to_many :posters, class_name: 'User', inverse_of: nil
#all callbacks switched off
end
So what I am trying to do is to create new User while being logged in as admin User. It worked fine until I introduced Conversation model. Then I started to get 401 after succesful creation of user and conversations. I checked logs, and noticed that on create of each Conversation I also get this for each of my posters:
MOPED: 127.0.0.1:27017 UPDATE database=blahblah_development collection=users selector={"_id"=>"54ee69e81d41c82b6c000001"} update={"$set"=>{"encrypted_password"=>"$2a$10$EPQXkBuYcd7rc1FiJTPngOlrpLAqw99O4Rja4zhuIMVzv838RQEyW"}} flags=[] (0.4256ms)
What? But it supposed to be many-to-zero, right? Each time encrypted_password is new, and then everything goes south despite that create action actually goes well: ... database stuff ends Redirected to http://ift.tt/1Fagc3P Completed 302 Found in 3283.6ms
Started GET "/admin/users" for 192.168.78.1 at 2015-05-25 03:07:01 +0200
Processing by UsersController#index as HTML
MOPED: 127.0.0.1:27017 QUERY database=blahblah_development collection=users selector={"$query"=>{"_id"=>"54ee69e81d41c82b6c000002"}, "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil (1.8945ms)
MOPED: 127.0.0.1:27017 QUERY database=blahblah_development collection=users selector={"$query"=>{"_id"=>"54ee69e81d41c82b6c000002"}, "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil (1.2648ms)
Completed 401 Unauthorized in 20.0ms
My ConversationsController is vanilla, and UsersController is simple too:
class UsersController < ApplicationController
before_filter :authenticate_user!
protect_from_forgery
def index
@users = User.all.asc(:last_name).paginate page: (params[:page] || 1)
end
...
end
What am I to do? Can I reference many-to-zero in a way that doesn't update my users collection, or at least not updating encrypted_password, which makes no sense? Or am I completely missing something? Serialized hash doesn't get affected at all, so I am a bit confused about the cause of session drop.
Stylesheets are not getting loaded while assets precompile
In assets.rb, I am using following code
def javascript_manifest_files(loc = '')
Dir.chdir("#{Rails.root}/app/assets/javascripts/") do
Dir["#{loc}*.js"]
end
end
def stylesheet_manifest_files(loc = '')
Dir.chdir("#{Rails.root}/app/assets/stylesheets/") do
Dir["#{loc}*.css"]
end
end
['', 'web/'].each do |loc|
Rails.application.config.assets.precompile += javascript_manifest_files(loc) + stylesheet_manifest_files(loc)
end
I am very new to rails, found this solution for assets pipelining to work.
For JS I am getting all the required javascritp but for stylesheets I am not getting the styles.
To call the stylesheets I am using this command
<%= stylesheet_link_tag 'application', media: 'all' %>
<%= stylesheet_link_tag "#{params[:controller]}", media: 'all' %>
When I am trying to open that page, geting following error. Someone please help me out to solve this issue.
Sprockets::Rails::Helper::AssetFilteredError at / Asset filtered out and will not be served: add `Rails.application.config.assets.precompile += %w( web/home_page.css
)
to
config/initializers/assets.rb` and restart your server
Remove duplicates from custom search query
I have a search method that combines the results from doing a fuzzy search using the fuzzily gem and doing a search in the tags used in acts_on_taggable gem.
if params[:search]
results = Post.find_by_fuzzy_title(params[:search])
tagged_results = Post.tagged_with("#{params[:search]}")
@posts = (Kaminari.paginate_array(results+tagged_results)).page(params[:page]).per(1)
else
The problem is that the returned query contains a concatenation of the two individual queries with duplicate results. What I would like to do is make sure a result is displayed only once even if it contains both a matching title and a matching tag to the search keywords.