samedi 28 février 2015

Ruby exclamation mark -printing next line


TENANT_NAME=gets.chomp('/\p{Alnum}/')

$first = TENANT_NAME.slice(0,1).capitalize

$second = TENANT_NAME.slice(1..-1)

EXPORT_PASSWORD="Export-"+ $first + $second + "!"

puts EXPORT_PASSWORD


I want to print EXPORT_PASSWORD in one-line, but when i am trying to print it prints ! from another line. I am using Ruby output:



devi123kumari
Export-Devi123kumari
!

passing child class method as function argument in ruby

There is a class Commerce and its constructor will initialize an object named commerce. LineItem is a class with in the Commerce class. LineItem class has a method named "ssm". when this method "ssm" is invoked it will initialize an object of another class named SSM. In our problem, we need pass to the "ssm" method as a function argument in another Test class.



def autoUpdate(docNum, type, varName, value)
type = method(Commerce::LineItem:ssm)
commerce.line_item.type.call(varName).set(value)
end


In the place of the function parameter 'type', it should be replaced by different method names from the class LineItem. However the above function autoUpdate throws an error. How to pass child class methods as function parameters in another class.


vendredi 27 février 2015

when using semantic_form_for accurs "ActionView::Template::Error (undefined method `my_leaders_path' for #

model:



class MyLeader < ActiveRecord::Base
extend Enumerize
belongs_to :interviewer
attr_accessible :interviewer_id, :is_leader, :content
enumerize :is_leader, :in => %w[yes no]
end


controller:



ActiveAdmin.register MyLeader, :namespace => :fieldwork do
form do |f|
render :partial => 'content'
end
end


rake routes:



batch_action_fieldwork_my_leaders POST /fieldwork/my_leaders/batch_action(.:format) fieldwork/my_leaders#batch_action
fieldwork_my_leaders POST /fieldwork/my_leaders(.:format) fieldwork/my_leaders#create
new_fieldwork_my_leader GET /fieldwork/my_leaders/new(.:format) fieldwork/my_leaders#new
edit_fieldwork_my_leader GET /fieldwork/my_leaders/:id/edit(.:format) fieldwork/my_leaders#edit
fieldwork_my_leader GET /fieldwork/my_leaders/:id(.:format) fieldwork/my_leaders#show
PUT /fieldwork/my_leaders/:id(.:format) fieldwork/my_leaders#update
DELETE /fieldwork/my_leaders/:id(.:format) fieldwork/my_leaders#destroy


_content.html.erb:



<div style="width:80%;margin-left:400px">
<%= semantic_form_for MyLeader.new do |f| %>
<%= f.input :interviewer_id, :as => :hidden%>
<%= f.input :is_leader%>
<%= f.actions do %>
<%= f.action :reset, :as => :button %>
<%= f.action :submit, :as => :button %>
<% end %>
<% end %>


The ERROR is:



ActionView::Template::Error (undefined method `my_leaders_path' for #<#<Class:0x007fadc5f8cdf0>:0x007fadc3d929e8>):


Why this happened: undefined method `my_leaders_path'? should that be fieldwork_my_leaders_path?


text_field with type :date doesn't get bound

This date field:



<%= f.text_field :my_date, id: 'id-123', type: 'date' %>


doesn't get bound to the value of my_date of the model on the, for example, edit page. When I load the page, it's always "empty".


enter image description here


Why is that? I also tried:



<%= f.text_field :my_date, id: 'id-123', type: 'date', value: '11/11/11' %>
<%= f.text_field :my_date, id: 'id-123', type: 'date', value: '11-11-11' %>


and it also didn't work.


Workless gem with MongoID - after_create callback isn't firing

I have a production application with Workless and DJ & MongoMapper running just fine - after a document is created in the delayed_jobs queue Workless starts a Heroku worker and works off the job - shuts it down when there are no more jobs - this is brilliant.


I'm migrating over to MongoId and I've found that Workless will not start up.


At first I thought it had to do with the failed_at field not being present on newly created documents in this collection which I created an issue for here: http://ift.tt/1ASsr50


But patching my own version of DJ to forcefully set this attribute to nil hasn't resolved the issue of the after_create callback not firing.


Has anyone ran into any issue with Workless gem where it won't start a worker on Heroku and your solution was NOT one of the following:



  1. Set Heroku API Key env var on Heroku app (done)

  2. Set Heroku APP name (done)

  3. Reset the above two just in case you messed something up (done)

  4. Accepted the API terms of service the first time you try to use a worker and set a form of payment (you can't get the API key without it if I recall - but done anyway)


?


I cannot figure the cause of after_create not firing when it should. I also couldn't successfully run the spec tests locally with workless, need more study of this gem to get that going.


Why do I get the error: TypeError in UsersController#create can't convert String into Hash

I am trying to implement a email functionality so that when someone registers they recieve an email. I am following this guide: http://ift.tt/KXJcBq


But I get the error:



TypeError in UsersController#create
can't convert String into Hash


application_mailer.rb:



class ApplicationMailer < ActionMailer::Base
default "from@example.com"
layout 'mailer'
end


user_mailer.rb:



class UserMailer < ApplicationMailer
default from: 'notifications@example.com'

def welcome_email(user)
@user = user
@url = 'http://localhost:3000/users/login'
mail(to: @user.email, subject: 'Welcome to My Awesome Site')
end
end


views/user_mailer/welcome_email.html.erb:



<!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
</head>
<body>
<h1>Welcome to example.com, <%= @user.name %></h1>
<p>
You have successfully signed up to example.com,
your username is: <%= @user.login %>.<br>
</p>
<p>
To login to the site, just follow this link: <%= @url %>.
</p>
<p>Thanks for joining and have a great day!</p>
</body>
</html>


views/user_mailer/welcome_email.txt.erb



Welcome to example.com, <%= @user.name %>
===============================================

You have successfully signed up to example.com,
your username is: <%= @user.login %>.

To login to the site, just follow this link: <%= @url %>.

Thanks for joining and have a great day!


And the create method in 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
UserMailer.welcome_email(@user).deliver_later
session[:user_id] = @user.id
redirect_to films_path
else
render action: "new"
end
end


Can someone please help.


Heroku Ruby on Rails app don't updates non-digested assets in public/assets dir

I have Ruby on Rails application on heroku.


We are using ruby 2.1.5



ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-linux]


And Ruby on Rails 4.1.1


Gemfile: http://ift.tt/1awG1mb


Sprockets version (extract from gemfile.lock):



sprockets (2.11.0)
hike (~> 1.2)
multi_json (~> 1.0)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
sprockets-rails (2.2.4)
actionpack (>= 3.0)
activesupport (>= 3.0)
sprockets (>= 2.8, < 4.0)




Of course we are using digested assets


e.g. application-d99ed24f47c5c39b96889148558cb16c.js - THEY are working


Besides that, I am using non-digested assets for CKEditor,


I put them under RAILS_ROOT/public/assets directory


so /assets/ckeditor/config.js should point to RAILS_ROOT/public/assets/ckeditor/config.js




Issue


I can't update assets under public/assets


I updated one file from CKEditor, but it doesn't show the changes either when I:



  • fetch file via CURL

  • look at source in incognito window at chrome (incognito -> 'avoid' caching)


I commited the changes, build on CircleCI passes (continuous integration service). Auto-deploy updates the staging server.


But I still get the old file.


MOREOVER I looked at source of the file using heroku run bash



heroku run bash
cd public/assets/ckeditor
cat config.js


and it RETURNS the old version. Changing this via various tricks e.g. rm cp echo NEW_CONTENT >> NEW_FILE.js also doesn't work.


Heroku returns old version...


PS Moving CKEditor from public/assets/ckeditor to app/assets/ckeditor didn't solve the issue.


Rails 3: Creating a form with nested attributes

I need to create a form that involves three hierarchies. For example, the form allows the user to create and edit the "company_apps" which belong to a particular company. Each of these "company_apps" can have one or more "app patterns". Creating a form for company_apps nested within a company seems simple enough but I'm confused on how to organize the form so that the user can create one or more app patterns for each particular company_app. Posted is a bullet points list of how I'm trying to arrange the form.



  • Company App Name, text_field

  • Company App Category, select_tag

  • Company App Tags, select_tag <- (Can have 0 or many) App Patterns (can have 0 or many)

  • App Pattern name, text_field

  • App Pattern classification, select_tag


comany.rb



class Company < ActiveRecord::Base
has_many :company_apps, :foreign_key => 'ca_company_id'
accepts_nested_attributes_for :company_apps
end


company_app.rb



class CompanyApp < ActiveRecord::Base
self.table_name = 'company_apps'
has_many :app_patterns, :foreign_key => 'ap_id'
belongs_to :company, :foreign_key => 'ca_company_id'
end


app_pattern.rb



class AppPattern < ActiveRecord::Base
belongs_to :company_apps, :foreign_key => 'ap_ca_id'
end


_form.html.haml



= form_for(@company) do |form|
%table
%tr
%td
%h2 Company Apps

%td
- companyApps = @company.company_apps
- tags = Tag.order_by(:tag_title).all.collect{ |t| [t.tag_title, t.tag_id] }
- selected = Hash.new

- companyApps.each_with_index do |ca, idx_ca|
- options = options_for_select(tags, ca.tag_ids)
- html_options = { :multiple => true, :size => 8, :class => 'chosen', 'data-placeholder' => 'Select Tags'}
%tr
%td
=label_tag ca.ca_name
%td
= select_tag "tag_ids[#{ca.ca_id}][]", options, html_options

%tr
%td
- categories = [['category1', 1], ['category2', 2], ['category3', 3], ['category4', 4], ['category5', 5], ['category6', 6]]
- options = options_for_select(categories)
= select_tag 'company[category_ids][]', options, :prompt => "Select Category"
%tr
%td
%h5 App Patterns
%tr
%td
%h2= form.label ca.app_patterns, "App Pattern Name:"
=form.text_field ca.app_patterns


%tr
%td
%h2 Save Button
%td.submit= form.submit("Save", :class => 'submit')
%tr
%td
%h2 Cancel Button
%td.submit= button_link("Cancel", companies_path, 'submit')


Do I need to add another nested attributes statement to one of my models? How do I arrange the form correctly? Currently, I am getting the following error:



undefined method `#<AppPattern:0x007f8ee71525e8>' for #<Company:0x007f8ee713b0a0>

Ruby on Rails Order By Using Associations

I currently have an order by working on my Ruby on Rails application so that on the Bookings index a user can order their bookings by show_date. This is done through the following in the bookings_controller:



def index
@bookings = Booking.joins(:showing).all.order(params.fetch(:sort, 'id asc'))
end


And the view code:



<form>
Order by:
<select name="sort">
<option value="show_date ASC">Show Date (Oldest First)</option>
<option value="show_date DESC">Show Date (Most Recent First)</option>
</select>
<button>
Go
</button>
</form>


But what I want to do is enable the user to order by the film's title as well as the show date. I have tried to do this with this code:


views/bookings/index.html.erb:



<form>
Order by:
<select name="sort">
<option value="show_date ASC">Show Date (Oldest First)</option>
<option value="show_date DESC">Show Date (Most Recent First)</option>
<option value="title ASC">Film Title (A-Z)</option>
<option value="title DESC">Film Title (Z-A)</option>
</select>
<button>
Go
</button>
</form>


And the bookings_controller:



def index
@bookings = Booking.joins(:showing, :film).all.order(params.fetch(:sort, 'id asc'))
end


But this doesn't work and I get the error:



ActiveRecord::StatementInvalid in Bookings#index

SQLite3::SQLException: no such column: film:
SELECT "bookings".* FROM "bookings" INNER JOIN "showings" ON
"showings"."id" = "bookings"."showing_id" ORDER BY film ASC


I think it is because their isn't an association between bookings and film.


Booking.rb:



belongs_to :user
belongs_to :showing
delegate :screen, to: :showing


Showing.rb:



belongs_to :film
has_many :bookings
belongs_to :screen


Film.rb:



has_many :showings
belongs_to :certificate
belongs_to :category

Is there any way to know which files Rails is opening when doing I18n?

I'm having trouble with translations (I18n) in Rails 3. There are a couple of words that I can't realize from where Rails/I18n is trying to read the translation.


My form has a simple_form inside a custom_form. Something like this:



<%= custom_form_for(@prospect) do |f| %>
<div class="row-fluid">
<div class="span4">
<%= f.input :usuario_id, :wrapper => :prepend, :label => false do %>
<%= f.label :usuario_id, :class => "add-on", :required => false %>
<%= f.input_field :usuario_id, :collection => @usuarios %>
<% end %>
</div>
<%= f.simple_fields_for :crm_dados_entidade_attributes do |cde| %>
<div class="span4">
<%= cde.input :origem_lead_id, :wrapper => :prepend, :label => false do %>
<%= cde.label :origem_lead_id, :class => "add-on", :required => false %>
<%= cde.input_field :origem_lead_id, :collection => @origem_leads %>
<% end %>
</div>
<% end -%>
</div>
<% end -%>


I have translation files for each model. For example: prospects.yml, leads.yml, and son on...


My problem is that the fields in the custom_form_for are translated correctly, but the fields in the simple_fields_for are not translated. Actually, the output for origem_lead_id is: 'Origem lead', when my translation file is like this:



pt-BR:
activerecord:
models:
'crm/crm_dados_entidades': 'Pessoa'
attributes:
'crm/crm_dados_entidade':
origem_lead_id: 'Origem do Lead'
origem_lead: 'Origem do Lead'


I've tried to put this code in several files and in different ways, like (prospects.yml, crm_dados_entidades.yml), attributes for ( 'crm/crm_dados_entidade', 'crm/prospects').


Nothing seems to work. So, my question is: Is there anyway to track where Rails/I18n is looking for the translation?


http://localhost:3000/users/new Routing Error

Im following this tutorial. http://ift.tt/1kmdoqc i just the part titled Adding Some Validations to the User Model


When i go to http://localhost:3000/users/new i get an routing error. But based on my knowledge the rout looks fine. Whats wrong?


user_controller.rb



class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
flash[:notice] = "You signed up successfully"
flash[:color]= "valid"
else
flash[:notice] = "Form is invalid"
flash[:color]= "invalid"
end
render "new"
end
end


routes.rb



Rails.application.routes.draw do
get 'users/new'

Casein notifications

Does anyone have any experience with upgrading the Casein gem when they upgrade to Rails3?


When I upgraded my app to Rails 3 I came across an issue with the Casein 3.1.0 gem.


It is breaking my cucumber tests with the following error:



undefined local variable or method `casein_config_email_from_address' for Casein::CaseinNotification:Class (NameError)
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/actionmailer-3.0.3/lib/action_mailer/deprecated_api.rb:74:in `method_missing'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/actionmailer-3.0.3/lib/action_mailer/base.rb:427:in `method_missing'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/casein-3.1.0/app/mailers/casein/casein_notification.rb:8:in `<class:CaseinNotification>'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/casein-3.1.0/app/mailers/casein/casein_notification.rb:6:in `<module:Casein>'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/casein-3.1.0/app/mailers/casein/casein_notification.rb:1:in `<top (required)>'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:239:in `require'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:239:in `block in require'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:227:in `load_dependency'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:239:in `require'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:346:in `require_or_load'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:300:in `depend_on'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:216:in `require_dependency'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/engine.rb:138:in `block (2 levels) in eager_load!'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/engine.rb:137:in `each'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/engine.rb:137:in `block in eager_load!'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/engine.rb:135:in `each'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/engine.rb:135:in `eager_load!'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/application/railties.rb:11:in `each'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/application/railties.rb:11:in `all'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/application.rb:107:in `eager_load!'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/application/finisher.rb:41:in `block in <module:Finisher>'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/initializable.rb:25:in `instance_exec'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/initializable.rb:25:in `run'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/initializable.rb:50:in `block in run_initializers'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/initializable.rb:49:in `each'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/initializable.rb:49:in `run_initializers'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/application.rb:134:in `initialize!'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/railties-3.0.3/lib/rails/application.rb:77:in `method_missing'
/Users/camillavk/Documents/Work/Saild/saild/config/environment.rb:7:in `<top (required)>'
/Users/camillavk/Documents/Work/Saild/saild/features/support/env.rb:8:in `require'
/Users/camillavk/Documents/Work/Saild/saild/features/support/env.rb:8:in `<top (required)>'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/cucumber-1.1.2/lib/cucumber/rb_support/rb_language.rb:143:in `load'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/cucumber-1.1.2/lib/cucumber/rb_support/rb_language.rb:143:in `load_code_file'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/cucumber-1.1.2/lib/cucumber/runtime/support_code.rb:171:in `load_file'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/cucumber-1.1.2/lib/cucumber/runtime/support_code.rb:83:in `block in load_files!'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/cucumber-1.1.2/lib/cucumber/runtime/support_code.rb:82:in `each'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/cucumber-1.1.2/lib/cucumber/runtime/support_code.rb:82:in `load_files!'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/cucumber-1.1.2/lib/cucumber/runtime.rb:137:in `load_step_definitions'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/cucumber-1.1.2/lib/cucumber/runtime.rb:39:in `run!'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/cucumber-1.1.2/lib/cucumber/cli/main.rb:43:in `execute!'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/cucumber-1.1.2/lib/cucumber/cli/main.rb:20:in `execute'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/cucumber-1.1.2/bin/cucumber:14:in `<top (required)>'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/bin/cucumber:23:in `load'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/bin/cucumber:23:in `<main>'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/bin/ruby_executable_hooks:15:in `eval'
/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/bin/ruby_executable_hooks:15:in `<main>'


But the method IS defined in the Casein::ConfigHelper:



module Casein::ConfigHelper

# Text string containing the name of the website or client
# Used in text and titles throughout Casein
def casein_config_website_name
'Casein'
end

# URL to the logo used for the login screen and top banner - it should be a transparent PNG
def casein_config_logo
'/casein/images/casein.png'
end

# The server hostname where Casein will run
def casein_config_hostname
if ENV['RAILS_ENV'] == 'production'
'http://ift.tt/1DyltTL'
else
'http://localhost:3000'
end
end

# The sender email address used for notifications
def casein_config_email_from_address
'donotreply@caseincms.com'
end

# The page that the user is shown when they login or click the logo
# do not point this at casein/index!
def casein_config_dashboard_url
url_for :controller => :casein, :action => :blank
end

# A list of stylesheet files to include in the page head section
def casein_config_stylesheet_includes
['/casein/stylesheets/custom.css', '/casein/stylesheets/screen.css', '/casein/stylesheets/elements.css']
end

# A list of JavaScript files to include in the page head section
def casein_config_javascript_includes
['/casein/javascripts/custom.js', '/casein/javascripts/casein.js', '/javascripts/prototype.js']
end

end


and when I look at the file it mentions (/Users/camillavk/.rvm/gems/ruby-1.9.3-p551@rails3/gems/casein-3.1.0/app/mailers/casein/casein_notification.rb:8:in `') it has this:



module Casein

require 'casein/config_helper'
include Casein::ConfigHelper

class CaseinNotification < ActionMailer::Base

default :from => casein_config_email_from_address

self.prepend_view_path File.join(File.dirname(__FILE__), '..', 'views', 'casein')
....
end


I don't know why it's not seeing the method and don't know if I'm meant to change the default :from => casein_config_email_from_address or not?


jeudi 26 février 2015

Is the `@count` an instance variable or class variable in Ruby?


class Counter
def self.counted_new
@count = 0 if @count.nil?
@count += 1
new
end

def self.count
@count
end
end


In format, @count looks like a instance variable, but when I load this in "irb"(interface ruby) and type four command code



Counter.counted_new
Counter.count
Counter.counted_new
Counter.count


@count finally became 2! acting like a class variable


Testing with rspec is causing an error: `Migrations are pending. To resolve this issue, run: bin/rake db:migrate RAILS_ENV=development `


when I run the rails server, localhost displays this error:

ActiveRecord::PendingMigrationError (Migrations are pending. To resolve this issue, run: bin/rake db:migrate RAILS_ENV=development):


I have run the bin/rake... and the next error says:




$ bundle exec bin/rake db:migrate RAILS_ENV=development
== 20150225172130 CreateVotes:
migrating ======================================
-- create_table(:votes)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: table "votes" already exists: CREATE TABLE "votes"
("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "value" varchar(255),
"user_id" integer, "post_id" integer, "created_at" datetime, "updated_at"
datetime)


_create_votes.rb



class CreateVotes < ActiveRecord::Migration
def change
create_table :votes do |t|
t.string :value
t.references :user, index: true
t.references :post, index: true

t.timestamps
end
end
end





Basically, it tells me I have migrations pending, but when I attempt to migrate it says the table already exists.






20150225172130 CreateVotes:
migrating ======================================
-- create_table(:votes)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: table "votes" already exists: CREATE TABLE "votes"...

.clone not cloning the dimension of image properly using paperclip

I have an array of elements which are being displayed with their repective images using thumbnail defined through paperclip. When the data is replicated through .clone method of jquery everything is fine but the image does not show as per the thumb.Instead it shows the original size.



var clone = $('.pick.cloner').clone().appendTo('.picks-wrap .inner');
$(clone).data('id', data.picks[pick][1]);
$(clone).find('strong').html("Pick " + data.picks[pick][2]);
$(clone).find('p').html(data.picks[pick][3]);
$(clone).find('img').attr('src', data.picks[pick][4]);
$(clone).addClass('entering').removeClass('cloner');


My html



.inner
.pick.cloner
%em.selecting
Selecting
%em.ondeck
On Deck
%strong
Pick #
= image_tag("default_small_logo.jpg")
%p
Team Name

- @league.draft.get_picks(12).each_with_index do |pick, index|
.pick{ :class => "#{'selecting' if index == 0 && @league.draft.running?}#{'ondeck' if (index == 1 && @league.draft.running?) || (index == 0 && !@league.draft.running?)}"}
%em.selecting
Selecting
%em.ondeck
On Deck
%strong.img_go
= "Pick #{pick.pick_order}"
= image_tag(pick.team.logo.url(:draft))
%p
= pick.team.name


In firebug


Step 1: When the page is loaded or refreshed



<img alt="My image" src="http://ift.tt/1EuxjA8">


Step 2: When the clone is called the image source becomes like this



<img alt="My image" src="http://ift.tt/1wjk4v3">


How does it changes the thumbnail from "draft" to "original" I am not able to understand that neither am I able to debug the source of image that it is picking up or changing. It would be really great if someone helps.


Active admin install error

I have an error, when try to run command:


rails g active_admin:install


The error is /home/user1/.rvm/gems/ruby-2.1.4@rails418/bundler/gems/active_admin-6bde1f57ec5f/lib/generators/active_admin/devise/devise_generator.rb:21:inrescue in install_devise': uninitialized constant ActiveAdmin::Generators::DeviseGenerator::DependencyError (NameError) ` Active admin and devise gems are install. The only problem is when I generate active admin. I use Rails-4.1.8 and ruby-2.1.4.


Thanks for help and good day.


The correct way to do inheritance in Rails mountable engine

Today, I found a very strange issue while writing a mountable engine using Rails 3. I have the following ApplicationController in my engine:



module Marketplace
class ApplicationController < ::ApplicationController
before_filter :merge_abilities

layout 'marketplace/application'

def marketplace_current_user
Marketplace::User.find(current_user.id)
end

private

def merge_abilities
current_ability.merge(Ability.new(current_user))
end
end
end


And my User model definition is



module Marketplace
class User < ::User
devise omniauth_providers: [:facebook, :paypal]

has_one :payout_identity, class_name: "Marketplace::PayoutIdentity"
has_many :course_purchases, class_name: "Marketplace::CoursePurchase"

def has_verified_payout_identity?
self.payout_identity and self.payout_identity.receiver_id
end
end
end


After starting up the rails server, the first request to load a page will have the controller run the marketplace_current_user method correctly and load the engine's User class. However any request after the first one will given a strange NameError - "uninitialized constant Marketplace::Marketplace::User".


I tried removing the namespace in marketplace_current_user definition but it will load the main app's User class instead.


At last when I change my ApplicationController to look like this:



class Marketplace::ApplicationController < ::ApplicationController
before_filter :merge_abilities

layout 'marketplace/application'

def marketplace_current_user
Marketplace::User.find(current_user.id)
end

private

def merge_abilities
current_ability.merge(Ability.new(current_user))
end
end


Everything would work fine.


Could someone enlighten me where I got it wrong at the beginning? Was it wrong to do inheritance that way?


mercredi 25 février 2015

I keep running into the following error "undefined method `user' for nil:NilClass"

Everything was working fine but I added stuff to my original scaffold, Specifically this line of code. "rails g migration add_first_name_and_last_name_to_users first_name:string last_name:string bio:text" After this I did "rake db:migrate" and added the fields. After working out the error I can't get past this new one.


Here is my users_controller.rb,



class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
after_action :signed_in_after_register, only: :create

def index
@users = User.all
@user = User.find(session[:user_id])
end

def dashboard
@user = User.find(session[:user_id]) unless session[:user_id] == ""
redirect_to login_path, notice: "You're not logged in" unless @user
@posts = @user.posts.order("created_at DESC").limit(3)
end

def newsfeed
@user = User.find(session[:user_id]) unless session[:user_id] == nil
redirect_to login_path, notice: "You're not logged in" unless @user
end

def nav
@user = User.find(session[:user_id])
end

def destroy
@user = User.find(session[:user_id])
end

def welcome
@user = User.find(session[:user_id])
end

def show
@user = User.find(session[:user_id]) unless session[:user_id] == ""
redirect_to login_path, notice: "You're not logged in" unless @user
@posts = @user.posts.order("created_at DESC").limit(3)
end

def new
@post = Post.new(params[:post_id])
@user = User.new
end

def edit

end

def create
@post.user = @current.user
@user = User.new(user_params)

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

def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to dashboard_path, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end

def destroy
@user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end

private
def set_user
@user = User.find(params[:id])
end
def signed_in_after_register
session[:user_id] = @user.id
end

def user_params
params.require(:user).permit(:first_name, :last_name, :bio, :name, :password, :password_confirmation, :email, :age, :profile_picture, :post)
end
end


This is in my _form.html.erb



<%= form_for @user, html: { multipart: true } 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 |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="sign_up_form_2">
<div class="field">
<%= f.label :first_name %>
<%= f.text_field :first_name, placeholder: "First Name", class: "form-control" %>
</div>
<div class="field">
<%= f.label :last_name %>
<%= f.text_field :last_name, placeholder: "Last Name", class: "form-control" %>
</div>
<div class="field">
<%= f.label :User_name %><br>
<%= f.text_field :name, placeholder: "User Name", class: "form-control" %>
</div>
<div class="field">
<%= f.label :email %><br>
<%= f.text_field :email, placeholder: "Email", class: "form-control" %>
</div>
<div class="field">
<%= f.label :age %><br>
<%= f.number_field :age, placeholder: "Age", class: "form-control" %>
</div>
<div class="field">
<%= f.label :password %><br>
<%= f.password_field :password, placeholder: "Password", class: "form-control" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br>
<%= f.password_field :password_confirmation, placeholder: "Password Confirmation", class: "form-control" %>
</div><br>
<div class="field">
<%= f.label :profile_picture %>
<%= f.file_field :profile_picture %><br>
</div>
<div class="actions">
<%= f.submit "Create Account", class: "btn btn-default btn-sign-up" %>
</div>

<% end %>
</div>


If there is any other code you need to see to get a better understand then please let me know! I've been stuck on this for an hour now and I'm sure its pretty simple, Thanks in advance!


Why mp4 stored in S3 is not working in audio tag?

I have a rails app with an audio player that plays an audio file stored in S3. The player works locally, but not in production (Heroku). The linked audio file plays fine when pasted in the browser. I am not posting code because I don't know where the problem is (if it is a code problem) and besides it works locally.


Anyone give me a gut feeling about what is happening?


Methods included not found after upgrading to Rails 4

After upgrading to Rails 4.2.0 from Rails 3.2.12, the following code in module WfHelper is broken:



def self.included(base)
base.before_action :load_wf_action_def
end


Here is base is the quotes controller. Method load_wf_action_def runs a eval to include some methods to make them available to quotes controller. In quotes controller, there includes:



include BizWorkflowx::WfHelper


None of the methods supposedly loaded by load_wf_action_def was there for quotes controller.


Which new feature in rails 4.2 could break the code? In debug, the QuotesController.public_instance_methods in Rails 4 does not return _one_time_conditions_valid_# which is imposed by execution of filter (action in Rails 4). In Rails 3, it does show the _one_time_conditions_valid_# for the before_filter executed.


Use angular js to submit file via rails paperclip

I'm trying to use angular to send a file as a param to rails, and then have rails save that file as a user attachment via paperclip. The furthest I've gotten is getting rails to upload something, but it ends up being a txt file with the single line 'object file'.


Here's the relevant Angular



a.uploadAnonRes = function(app){
if(window.FileReader){ console.log("supported")};
console.log(($('.anonUploadField'))[0].files);
http = {
method: "PUT",
url: '/admin/upload_anon_res.json',
params: {
anon_file: btoa(($('.anonUploadField'))[0].files[0]),
user_id: app.raw_app.user_id
}
};
$http(http).success(function(data){
console.log("success");
});
};


Here's the relevant rails



def upload_anon_res
user = User.find(params[:user_id])
user.anon_resume = decode_res
user.save
respond_to do |format|
format.json{ render json: user, root: false }
end
end

def decode_res
decoded_data = Base64.decode64(params[:anon_file])
data = StringIO.new(decoded_data)
return data
end


As a last note, the file types that I'm trying to work with are doc/docx. I'm trying to avoid adding new dependencies, but if there's no other good way, then so be it. I really appreciate any help/suggestions.


Using multiple sidekiq databases

Hey I am attempting to spawn a sidekiq worker that connects to a completely separate Redis database. I know with 3.0's connection pooling this is possible, and I have been able to successfully push a job onto the correct Redis DB, but the problem is the Sidekiq web UI is not showing these jobs in the queue (I have mounted a separate Rack app for this that points exclusively to the other Redis DB). The "Busy" tab in the admin interface also shows my sidekiq workers that I have pointed at this DB, with correct PIDs.


Here's my sidekiq.rb:



Sidekiq.configure_server do |config|
if ENV['REDIS_DB'] == "2"
config.redis = { :url => "http://redis#{SIDEKIQ_HOST}:6379/2", :namespace => 'drip' }
else
config.redis = { :url => "http://redis#{SIDEKIQ_HOST}:6379", :namespace => 'drip' }
end
end

Sidekiq.configure_client do |config|
if ENV['REDIS_DB'] == "2"
config.redis = { :url => "http://redis#{SIDEKIQ_HOST}:6379/2", :namespace => 'drip' }
else
config.redis = { :url => "http://redis#{SIDEKIQ_HOST}:6379", :namespace => 'drip' }
end
end


My use case is that I need to have fine grain control over the jobs that go into the second database, so I need the workers configured precisely so they are only using as many resources as I need them to. I only want the workers that are configured in this way to pick up these jobs.


How to manually run a Sidekiq job

I have an application which uses Sidekiq. The web server process will sometimes put a job on Sidekiq, but I won't necessarily have the worker running. Is there a utility which I could call from the Rails console which would pull one job off the Redis queue and run the appropriate Sidekiq worker?


Paperclip route file with dots in name

I have the following route:



resources :projects do
resources :uploads, :only => [:destroy] do
member do
get ':filename', to: :download, as: :download
end
end
end

download_project_upload GET /projects/:project_id/uploads/:id/:filename(.:format) uploads#download


Here's the relevant part of my upload model



class Upload
has_attached_file :item,
:url => "/projects/:project_id/uploads/:id/:style_:basename.:extension",
:path => ":rails_root/public/:class/:attachment/:id/:style_:basename.:extension"


The problem is when I go a URL like the following:



http://mysite/projects/3902/uploads/5634/some.file.withdots.pdf


I get a routing error. How can I resolve this? The route looks correct to me.


Note: I only get the routing error on files which have dots in the names. If the file has no dots or uses underscores the route resolves as expected. Renaming all filenames to parse the dots out is not an option.


How to convert a webpage contenet into text format in ruby on rails and How to write google search engine in ruby on rails project


  • How to write google search engine in ruby on rails project?

  • How to parse web page data into a text formate ? I need a some text in text box then press check button.The resulted wanted web page links .But what we mention text in text box that must be match any one statements .Let me know how to do this task .what type of technology easy for this task.please think and give a good answer .


Gitbash Error - rbenv: cannot find readlink - are you missing GNU coreutils?

Hello when i open git hub i get an error right at the top.


It literally looks like this:



rbenv: cannot find readlink - are you missing GNU coreutils?
rbenv: cannot find readlink - are you missing GNU coreutils?

Joey@JOEY-PC /c/Sites (master)


$


Everything was working great before i installed rubyinstall 1.9.3.


Then my local server wasn't working when i tried to run a new website im making.


So i reverted back to ruby 2.1.5p273 by running rubyinstaller 2.1.5


Anyone know what the problem is?


Here is what my server looks like when once the above error started to appear on gitbash


http://ift.tt/1Da7bpF


Rails custom field_with_errors Proc

I have some markup as follows:



<div class="form">
<input type="text" name="user[email]" id="user_email" data-validate="true">
<label data-content="Your email"></label>
</div>


I am currently using client_side_validations to check and edit the markup to:



<div class="form">
<input type="text" name="user[email]" id="user_email" data-validate="true">
<label data-content="Your email"></label>
<span class="input-error" data-error-id="1">EMAIL IS EMPTY</span>
</div>


If, however, the user were to still submit the form somehow I would need to replicate the same behaviour from Rails' ActionView::Base.field_error_proc = Proc.new do |html_tag, instance| method. All I need to do is add a <span> tag, as above (the id isn't needed via Proc), to the end of the parent in which the <input> tag is contained.


How can I achieve this via Proc?


mardi 24 février 2015

Joining Multiple table to fetch email id

I have 3 models


aff.rb



has_many :tic_affs, inverse_of: :aff, dependent: :restrict_with_exception
has_many :tic, through: :tic_affs


tic.rb



has_one :tic_aff, inverse_of: :tic, dependent: :restrict_with_exception
has_one :aff, through: :tic_aff


use.rb



has_one :aff, inverse_of: :use, dependent: :restrict_with_exception
has_many :tics, class_name: "Tic"


i want to fetch email id from user table using joins could any one please help me in framing the Rails query


This is the query i wrote to fetch email id's



select users.email
from ticket_affiliates
FULL OUTER JOIN affiliates ON ticket_affiliates.affiliate_id=affiliates.id
JOIN users ON affiliates.user_id=users.id;


if this query is right help me framing this into rails query


Using attr_accessible, whiltelist disabled, and I STILL can't mass assign attributes

So I am working on my first rails app and I can't seem to get past this error. I apologize if I don't provide enough information, I am still new to this stuff.


Here is the model I am trying to use:



class Movie < ActiveRecord::Base
attr_accessible :tilte, :rating, :description, :release_date
end


After a bit of searching, I discovered I should be able to force it to work if I disabled the white list by setting config.active_record.whitelist_attributes = false in the /app/config.rb which I did in an attempt just to bypass the issue for this assignment, yet I am STILL not able to mass assign attributes.


This is the specific error message that I am receiving: ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: title


And here is the code I am trying to execute from the rails console:



#### Create
starwars = Movie.create!(:title => 'Star Wars',
:release_date => '25/4/1977', :rating => 'PG')
# note that numerical dates follow European format: dd/mm/yyyy
requiem = Movie.create!(:title => 'Requiem for a Dream',
:release_date => 'Oct 27, 2000', :rating => 'R')
# Creation using separate 'save' method, used when updating existing records
field = Movie.new(:title => 'Field of Dreams',
:release_date => '21-Apr-89', :rating => 'PG')
field.save!
field.title = 'New Field of Dreams'
#### Read
pg_movies = Movie.where("rating = 'PG'")
ancient_movies = Movie.where('release_date < :cutoff and rating = :rating',
:cutoff => 'Jan 1, 2000', :rating => 'PG')
#### Another way to read
Movie.find(3) # exception if key not found; find_by_id returns nil instead
#### Update
starwars.update_attributes(:description => 'The best space western EVER',
:release_date => '25/5/1977')
requiem.rating = 'NC-17'
requiem.save!
#### Delete
requiem.destroy
Movie.where('title = "Requiem for a Dream"')
#### Find returns an enumerable
Movie.where('rating = "PG"').each do |mov|
mov.destroy
end


Any advice?


Add Custom Styles to Rails Video Player

There are various services like PandaStream and SublimeVideo that allow you to embed their service into your rails project. You can use their video players to show streaming content. I would rather design the user interface of the rails video player myself. Even though I've tried accomplishing this using stylesheets the video player never changes in the rails app. What is the proper way to customize the look of the default rails video player?


Is there a "canvas_tag" feature for Ruby on Rails?

I am trying to use the HTML5 canvas features in a web application. Because there is image_tag and video_tag, I want to know if canvas_tag exist. If so, how do you implement it?


Register multiple Rails generators to be run on single invocation

On Rails3, I have multiple gems which by default rely on YAML config files placed in conf/gem1.yml, conf/gem2.yml, etc; these files should not be checked into source control as they have user-specific values such as secret tokens.


I'm looking for a way for each gem to define a generator that will create an initial version of that file for each dev to modify afterwards, and have those generators registered somehow so they can all be run by invoking a single command.


For example, I'd like gem1, gem2 and gem3 to define gem1:config, gem2:config and gem3:config generators, as well as a shared gems:all_config. So if I include gem1 and gem2 in my project, I automatically have the gems:all_config generator that will invoke gem1:config and gem2:config; if I add gem3 later, gem3:config is automatically appended to the call to gems:all_config.


Any ideas on how to implement this cleanly? I've been playing around with hook_for with no success so far, as it seems to be designed for a different use case.


Ruby's DateTime class strptime method is subtracting a day from my date object?

Here is the section of the controller that matters:



ap "START DATE IN THE CONTROLLER IS "
ap @selectedJob.start_date
@selectedJob.start_date = DateTime.strptime(@selectedJob.start_date.to_s, ('%m-%d-%Y'))
ap "AFTER THE STRPTIME METHOD"
ap @selectedJob.start_date


I wanted to know what the start_date was before and after my little method - I'm formatting the date part of the date object for display in a start_date input box in the view.


Here is the console output of the above:



"START DATE IN THE CONTROLLER IS "
Sat, 15 Feb 2014
"AFTER THE STRPTIME METHOD"
Fri, 14 Feb 2014


Why is Datetime.strptime subtracting a day from my date object?


When I change DateTime to Time class and call strptime - it correctly formats to Feb 15. What is it about DateTime that's not working and should I discontinue using it?


Ruby on Rails method to count multiple fields using where

In my Ruby on Rails application I am creating a cinema system, and when a user is logged on they can click "My Bookings" which will list all of their bookings. (Note, when a user books a showing they choose the amount of adult seats, child seats, senior seats, and student seats). On this page I want to display the amount of seats the user booked for that showing, so rather than saying adult seats: 1, child seats: 3, senior seats: 2, it would display seats booked: 6.


I have started to create a method to do this in booking.rb model:



def user_booked_seats_quantity_for_showing
user = User.find(session[:user_id]).id
showing = booking.showing_id
self.where("user_id = ? and showing_id = ?", user, showing)
end


But am unsure how to get the method to add up the data in the attributes: adult_seats, child_seats, senior_seats, and student_seats, where the user_id is the user currently logged in and the showing_id is that particular showing.


Can anyone help?


It is also worth noting that this is for the views/bookings/index so if a user has multiple bookings it will list all of them.


Rails controller filters magically reappearing after having been removed

I'm seeing very odd behaviour, where whether or not a filter is run seems to depend on whether it was set to run in the first spec to use that controller.


So I've reduced this down to a minimal controller:



class WtfController < ActionController::Base
before_filter :raise_error

def index
render nothing: true, status: 200
end

private
def raise_error
raise OMGError
end
end


(OMGError just subclasses StandardError)


And a test case:



describe 'wtfspec' do
it 'with filter' do
expect do
controller = set_up_controller
controller.process(:index)
end.to raise_error
end

it 'without filter' do
expect do
controller = set_up_controller
controller.class.skip_filter :raise_error
controller.process(:index)
end.not_to raise_error
end
end

def set_up_controller
controller = WtfController.new
controller.request = ActionController::TestRequest.new
controller.response = ActionController::TestResponse.new
controller
end


The filter should be skipped in the second test, but it isn't.


If the first expect block is not run, then the second test passes. It's only if it is run that the second fails. Similarly, if I skip_filter in the first test and use before_filter to readd it for the second test, the second fails to run the filter even though it should.


Here's the thing - if I examine the list of filters set on WtfController (using controller.class._process_action_callbacks.map(&:filters)) in the spec (in the second test) right before the controller.process line, then it has indeed been successfully removed, the skip_filter line works fine. But if I examine it inside the controller (in raise_error), it seems to have somehow been readded!


Note 'readded', not 'reappeared': The object_id of the raise_error callback that actually runs is different to the original one (the one that was there before running skip_filter). But the object_id of the array of filters (actually an ActiveSupport::Callbacks::CallbackChain) remains the same, as is the controller.


The behaviour is the same whether each of the two tests new's up a new controller object or reuses the same one (as you'd expect, since the filters are a property of the WtfController class object, not the instances).


I've spent a day debugging this and am utterly mystified. Any insight appreciated. Rails version is 3.2.21. Thanks :)


Disable asset fingerprinting

I am trying to disable asset fingerprinting by placing the following line in my config/environments/production.rb:



config.assets.digest = false


However, rails isn't honoring this and still compiling assets with a fingerprint in public/assets/:



bear-e1d6322cce5569e1c88e51d726af8f49.jpg


Why is rails ignoring this? Follow up question: if rails is stubborn about fingerprinting assets, why won't it change the name of the asset in the html.erb file so that the browser will know the right name of the file to request?


Returning Columns from Associated Table in Model.all

Summary:


I have a model with a few "belongs_to" associations and when I call Model.all (or another custom method if need be) I want to not only return all columns of Model, but also one column from each of the associated Models. Basically instead of just returning the ID's of the associated Models I want to get a more friendly attribute like "name".


Using Rails 3.2.x


Model Details:


I have five models, basically for data normalization.



class ActionItem < ActiveRecord::Base
belongs_to :action_item_status
belongs_to :prod_ops_acceptance
belongs_to :action_item_priority
belongs_to :incident_ticket
<truncated the rest>
end

class IncidentTicket < ActiveRecord::Base
attr_accessible :number
has_many :action_items
validates_presence_of :number
end

class ActionItemPriority < ActiveRecord::Base
attr_accessible :name
has_many :action_items
validates_presence_of :name
end

class ActionItemStatus < ActiveRecord::Base
attr_accessible :name
has_many :action_items
validates_presence_of :name
end

class ProdOpsAcceptance < ActiveRecord::Base
attr_accessible :name
has_many :action_items
validates_presence_of :name
end


Attempted Solutions:


I've tried many combinations of things including using ActionItem.includes and ActionItem.joins to no avail. The latest thing I tried is (trying only for the 'number' attribute of the IncidentTicket model to start with...)



ActionItem.all(
select: 'action_items.title, incident_tickets.number',
joins: 'INNER JOIN incident_tickets
ON action_items.incident_ticket_id = incident_tickets.id')


The above only returns the 'title' attribute from the ActionItem model and not the 'number' attribute from the IncidentTicket model despite the SQL looking correct. It seems like the SELECT on the joined table is completely ignored no matter what I try.


Obviously I am seriously missing something here or doing this completely wrong. I feel like there is some ActiveRecord magic that I'm missing out on that makes this trivial. Any help would be much appreciated! Please let me know if you need more details, I feel like this is kind of difficult to explain...


Creating tables from a cloned app sqlite3 Rails

I'm very new to sqlite3 and can't seem to figure out how to get it to create tables.


I have the code for a Rails app that I am updating to Rails 3.0.3 from Rails 2.3.12. I had managed to get the database working when it was still Rails 2.3.12, however since I upgraded Rails it seems to have 'lost' the tables and I can't figure out how to recreate them.


When I do bundle exec rake db:create it says that the test and development databases already exist.


However, when I do bundle exec rake db:migrate it says



rake aborted!
Could not find table 'comments'


All of the migration files are still there, as is the schema, but I don't know how to create the tables?


Rails multiple records select and apply multiple actions

I am quite new at rails and I am having some trouble designing an admin dashboard.


What I want to achieve is this:


Have a list of multiple users from database.


Have the ability to select multiple records.


Have the ability to apply different actions to all of the selected records.


The actions MAY not be directly translatable into SQL queries. (for example send an email)


I am not looking for a complete solution to the problem just a general description on how to approach this. I have a feeling I started on a wrong path.


So far I am doing this:


view



<%= form_tag("some_path", method: "get") do %>
<% @users.each do |user| %>
<%= check_box_tag "user_ids[]", users.id %>
<%end%>
<%end%>


controller



def send_email
@recipients = User.find(params[:user_ids])
@recipients.each do |recipient|
Notifier.raw_email(recipient.email, params[:user_email][:subject], params[:user_email][:body]).deliver
end
end


This works as it is but i can only apply one action, send email that is. I want to be able to choose an action to apply to all selected records or apply multiple actions to the selected records


Any thoughts?


Piece of code in textile

I have to put piece of code, that won't be removed by parser or anything else. In my html version code looks like <span>[~username]</span> How do i write something similar? I only need to save [~username] part, because thats what parser removes(square brackets) and my code doesn't work


How to get a list of active-record objects in an instance variable by looping through it with some condition?

I have an Exam model. I want to get all records that satisfy a condition in an instance variable.


I tried this in my controller:



@exam_list = Exam.all
@exams = []
@exam_list.each do |exam|
if conflict?([current_exam.exam_date, current_exam.end_date],[exam.exam_date, exam.end_date])
@exams << e
end
end


But its not working.


lundi 23 février 2015

Setting an id as a default foreign key in rails

I am having challenges assigning a current user a role in a team the user is creating. I want to assign the user that creates the team the role of the captain which could be changed later.

I'm currently using the create_asociation method that comes with has_one relationship, as this instantiates the values of the associated model, which i want to be instantiated with the current user but get the error Can't mass assign protected attribute: captain. Captain is a self join model with user as i will like to use captain.teammates and team.captain. Below are the models involved.


User and Captain Model



class User < ActiveRecord::Base
has_one :profile

has_many :teammates, :class_name => "User", :foreign_key => "captain_id"
belongs_to :captain, :class_name => "User"

belongs_to :team

# before_create :build_profile
after_create :build_default_profile

accepts_nested_attributes_for :profile
attr_accessible :email, :password, :password_confirmation, :profile_attributes, :captain_id

def build_default_profile
Profile.create(user_id: self.id)
end

has_secure_password

before_save { email.downcase! }
before_save :create_remember_token

VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true

private

def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end


Team Model



class Team < ActiveRecord::Base
has_many :profiles, through: :users
has_one :captain, :class_name => "User", foreign_key: :captain_id
has_one :result, as: :result_table

attr_accessible :teamname, :color, :result_attributes, :captain_attributes

after_create :build_result_table
after_create :build_default_captain
accepts_nested_attributes_for :profiles
accepts_nested_attributes_for :captain
accepts_nested_attributes_for :result

def build_result_table
Result.create(result_table_id: self.id, result_table_type: self.class.name)
end

def build_default_captain
# Team.captain = User
# Captain.create(team_id: self.id, captain_id: user.id)
end
end


User Controller



class UsersController < ApplicationController
before_filter :signed_in_user, only: [:index, :edit, :update, :destroy]
before_filter :correct_user, only: [:edit, :update]
before_filter :admin_user, only: :destroy

def new
@user = User.new
end

def create
@user = User.new(params[:user])
if @user.save!
sign_in @user
flash[:success] = "Welcome to the JHDC Mini Olympics Web Application; Thanks for singing Up"
redirect_to user_profile_path(@user, @profile)
else
flash[:error_messages]
render 'new'
end
end

def show
@user = User.find(params[:id])
end

def index
@users = User.paginate(page: params[:page])
end

def edit
@user = User.find(params[:id])
end

def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user])
flash[:success] = "Profile Updated"
redirect_to user_profile_path(@user, @profile)
else
render 'edit'
end
end

def destroy
User.find(params[:id]).destroy
flash[:success] = "User deleted."
redirect_to users_url
end

private

def signed_in_user
unless signed_in?
store_location
redirect_to signin_url, notice: "Please sign in."
end

def correct_user
@user = User.find(params[:id])
redirect_to(root_path) unless current_user?(@user)
end

def admin_user
redirect_to(root_path) unless current_user.admin?
end

def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end
end


Team Controller



class TeamsController < ApplicationController

def new
@team = Team.new
end

def create
@team = Team.new(params[:team])
@captain = @team.create_captain(captain: current_user)
if current_user.admin?
if @team.save!
flash[:success] = "Team created."
redirect_to @team
else
flash[:error_messages]
render 'new'
end
else
flash[:error] = "Sorry, you don't have the authority to create a Team"
redirect_to current_user
end
end

def index
@teams = Team.paginate(page: params[:page])
end

def show
@team = Team.find(params[:id])
end

def edit
if current_user.admin?
@team = Team.find(params[:id])
else
flash[:error] = "Sorry you dont have the authourity to edit a Team"
redirect_to current_user
end
end

def update
@team = Team.find(params[:id])
if @team.update_attributes(params[:team])
flash[:success] = "Team Updated"
redirect_to @team
else
render 'edit'
end
end

def destroy
Team.find(params[:id]).destroy
flash[:success] = "Team is deleted."
redirect_to teams_url
end


private

def team_params
params.require(:team).permit(:teamname, :color)
end
end


The admin is currently a way i'm using to restrict the user that can create a team but i plan to use gems like declarative authorization to create role based authorization. Thanks


Restrict the maximum quantity to select in a drop down to the value returned from a method

In my Ruby on Rails application I currently have the methods:



def remaining_seats
seats.count - bookings.sum(:seats_quantity)
end

def screens_info
"#{name} (#{remaining_seats}/#{seats.count} remaining)"
end


Which return the amount of seats that are available to be booked, for example if there have been two bookings which have booked 6 seats each in a 20 screen cinema it'll say there are 8/20 remaining.


What I want to do is use this so that in this drop down menu where the user selects the amount of seats they require:



<%= f.select :seats_quantity, '1'..'10' %>


Rather than having the range 1-10 the user can only select a quantity up to the amount of seats remaining. So, from the above example, if there are 8 seats available the user could select up to 8 seats from the drop down menu.


Ideally what I would like is to have a restriction of the maximum amount of seats being selected as 10, then if there are 9 available it would go to 9 or if there are only 3 seats available it would have the maximum of 3.


How can I do this?


Why does my method not work?

In my cinema ruby on rails application I am trying to display the amount of seats that have been booked for a showing in a screen. I have taken code from this question: Count the amount of records are associated to another record


And so have added this code to my screens.rb model:



def remaining_seats
seats.count - ( bookings || [] ).count
end

def screens_info
"#{name} (#{remaining_seats}/#{seats.count} remaining)"
end


And display this on the view:



<%= @booking.showing.screen.screens_info %>


But the code in remaining_seats: ( bookings || [] ).count returns 0, so the whole thing will tell me all seats are available.


This is my screen.rb model:



class Screen < ActiveRecord::Base
has_many :seats
has_many :showings
has_many :bookings, through: :showings
def screens_info
"#{name}"
end

def self.showing_search(showing_id)
if not showing_id.blank?
screen = Showing.find(showing_id).screen_id
self.where("id = ?", screen)
end
end

def remaining_seats
seats.count - ( bookings || [] ).count
end

def screens_info
"#{name} (#{remaining_seats}/#{seats.count} remaining)"
end
end


showing.rb:



class Showing < ActiveRecord::Base
belongs_to :film
has_many :bookings
belongs_to :screen
end


booking.rb:



class Booking < ActiveRecord::Base
belongs_to :user
belongs_to :showing
end


And the schema:



create_table "seats", force: :cascade do |t|
t.string "seat"
t.integer "screen_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

create_table "showings", force: :cascade do |t|
t.date "show_date"
t.time "show_time"
t.integer "film_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "screen_id"
end

create_table "screens", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

create_table "bookings", force: :cascade do |t|
t.integer "user_id"
t.integer "showing_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "seats_quantity"
end


So just to clarify, what I am trying to do is display the amount of seats that are available to be booked for a particular showing in a specific screen - so say a screen has 25 seats and at the 13:00 showing 5 seats have been booked I want to say there are 20 seats remaining.


Count the amount of records are associated to another record

In my Ruby on Rails application I am creating a cinema system, and on the bookings/new page I am allowing the user to choose the amount of seats they require through a drop down menu. But what I want to do is display the number of seats that are currently free in the screen, for example if a screen has 50 seats and 7 have been booked I want the system to display: "There are 43 seats available." I know I will need a method for this but am unsure about how I would implement it and how I would show this message.


It is worth noting that a seat would only be booked for one showing, so it would be free for others, which means that the method would have to be able to count the amount of seats available for that showing.


Can someone please help.


bookings/form.html.erb:



<%= form_for @booking do |f| %>
<%= f.hidden_field :user_id %>
<%= f.hidden_field :showing_id %>

<%= image_tag "thor_hammer.jpg",:size => "900x250" %>
<h1>NEW BOOKING:</h1>
<tr>
<td width="350px">
<br><%= f.label :seats_quantity, 'Please Select The Amount of Seats Required:' %>
</td>
<td width="300px">
<br><%= f.select :seats_quantity, '1'..'10' %><br>
</td>
<td width="300px">
<div class="actions">
<br><%= f.submit 'Book Showing' %>
</div>
<br><%= render "/error_messages", :message_header => "Cannot save: ", :target => @booking %>
</td>
</tr>
<% end %>


Screen.rb:



class Screen < ActiveRecord::Base
has_many :seats
has_many :showings
def screens_info
"#{name}"
end
end


Seat.rb:



class Seat < ActiveRecord::Base
belongs_to :screen
end


Booking.rb:



class Booking < ActiveRecord::Base
belongs_to :user
belongs_to :showing
end


Showing.rb:



class Showing < ActiveRecord::Base
belongs_to :film
has_many :bookings
belongs_to :screen
end


Schema:



create_table "bookings", force: :cascade do |t|
t.integer "user_id"
t.integer "showing_id"
t.integer "seats_quantity"
end

create_table "screens", force: :cascade do |t|
t.string "name"
end

create_table "showings", force: :cascade do |t|
t.date "show_date"
t.time "show_time"
t.integer "film_id"
t.integer "screen_id"
end

create_table "seats", force: :cascade do |t|
t.string "row_letter"
t.integer "row_number"
t.integer "screen_id"
end


It is worth noting that whilst the seats table contains the attributes row_letter and row_number a user IS NOT booking a specific seat, just the quantity of seats they require.


Behavior of the '*' operator in Array in Ruby

I am a newbie in Ruby. Please explain how the * operator works in this case.



arr = [1,2,3]
p arr
arr = *[1,2,3]
p arr
*arr = [1,2,3]
p arr
arr = [1,2,3]
p *arr


OUTPUT


[1,2,3]


[1,2,3]


[1,2,3]


1


2


3


What is happening in the last case ? Is it behaving as a iterator ? Can anyone give an example as to how to use it ? Also why it has no effect in the second and third case ?


dimanche 22 février 2015

Not loading dataTables.fixedColumn.js

Unable to add fixed column feature for a table by using gem 'jquery-datatables-rails'


couldn't find file 'dataTables/extras/dataTables.fixedColumn' (in /home/test-user/APP_TEST/app/assets/javascripts/application.js:16)


single login page in devise gem for two type of user

Using Devise gem :-


in my application i have two type user 1) Company 2) Employee


i have two separate model for both user and i want to give single sign-in page for both user


i already generate different views for both user using devise but then also i need single sign-in.


so how it is possible please help me out...!!!!!!!!!


i try this:- controllers/compnaies/sessions_controller.rb



def create
@employee = Employee.new
@company = Company.new
if @company.email_exist?(params[:company][:email])
super
elsif @employee.email_exist?(params[:company][:email])
params[:employee]=params[:company]
redirect_to employee_session_path(params)
end
end


employee_session_path is the path of employees's sessions create method but it always call new method of employees's sessions


controllers/employees/sessions_controller.rb



def create
super
end


email_exist? method check the email id in both model which is provided by any of user


in my model:


company.rb



def email_exist?(email)
if Company.find_by(email: email)
return true
end
end


employee.rb



def email_exist?(email)
if Employee.find_by(email: email)
return true
end
end


Thanks in advance...!!!!!!!!


How to check a datetime duration exists in another datetime duration?

I am developing a Rails application for Examination management.


Exams can be created for a time period.


Exam model have the fields start_date:datetime and end_date:datetime


Exam creation is a 2 step process. In the first step all the exam details including start_date and end_date is given.


In the second step I want to list all exams that have a conflicting time period with the current exam so that the user can choose whether to continue or not.


Example:


Current exam:



Start date and time: "2015-02-23 10:30:00"

End date and time: "2015-02-23 13:30:00"


Conflicting exam:



Start date and time: "2015-02-23 12:30:00"

End date and time: "2015-02-23 14:30:00"


How is it possible?


how to load a controller in another controller in ruby on rails

Like php we can import all the functionality of a simple php file name as myfile.php in another file index.php using require "", require_once "", include "" and include_once "". Like this in ruby on rails I want to import a controller file name as products_controller.rb in a another controller file name as home_controller.rb . both files present in the app/controller directory. In shot i want to import a controller file in another controller file to use all the functions of included controller file


Dynamic rails controllers and views without any code

I am looking for ways to reduce the default code for models, controllers and views.


I have just created a model SearchDescription with two fields and with a controller and view. I need the default scaffolded index,show etc. Also the rspecs, but again completely default. Nothing special. Just the default.


But as it turned out I am current committing some 20 files that are with a completely default behaviour. Nothing special.


Is there a way to do it cleaner with less code actually being generated in the project, but rather "dynamically generated"?


For example just write the following thing in a config file: SearchDescription, field1, field2; with Controller; with views; with rspecs


and have this work by convention without actually generating the files?


Can rails engine override main application's routes

I am writing a Rail 3 engine to add some marketplace functionality to an existing app. The existing app has an item description page and I am going to add some extra elements that will be used by the marketplace to that page. When the user visits the item page using the main app's route, I would like to use the engine's controller and view to render the page so that the new elements will be displayed. Effectively the engine will override some of the main application's routes. Can this be achieved?


samedi 21 février 2015

Automatic creation record after save

How do I replicate data of tbl1. in tbl2 after save?


Structure


Tbl1. Customer


id | first_name | last_name | address


Tbl2. Address


id | customer_id | address


vendredi 20 février 2015

How can i save values in database using rails association?

Can anybody please help me to resolve my small issue ?Actually i have Admin model and it has many images which will be stored in Image model.I am facing little bit problem to store some images in Image table via Admin model.I am giving my codes below.Please help me to resolve this issue.


Please check my below codes:


views/posts/adminpage.html.erb:



<div class="name-div">
Name:<%= @admin.email %>
</div>
<% if signed_in? %>
<div class="button-div">
<a href="/sessions/destroy"><button type="button" class="styled-button-10">LOG OUT</button></a>
</div>
<% end %>
<h1>WEBSITE USER DETAILS</h1>
<table class="gradienttable">
<tr>
<th><p>User id</p></th>
<th><p>User name</p></th>
<th><p>User email</p></th>
<th><p>User image</p></th>
</tr>
<% @posts.each do |post| %>
<tr>
<td><p><%= post.id %></p></td>
<td><p><%= post.name %></p></td>
<td><p><%= post.email %></p></td>
<td><p><%= image_tag(post.picture_url, :width => 90,:height => 90 ) if post.picture.present? %></p></td>
<td><p><%= link_to 'Delete', posts_deluser_path(:id => post.id), :confirm => 'Are you sure?',
:method => :delete %> </p></td>
</tr>
<% end %>
</table>
<center><h1>Add content</h1></center>
<table class="img-table">
<tr>
<th>Add 1st image</th>
<th>Add 2nd image</th>
<th>Add 3rd image</th>
<th>Add 4th image</th>
<th>Add 5th image</th>
</tr>
<%= form_for :images,:url => {:action => "addimage",:controller => "images",:id => @admin.id } do |f| %>
<tr>
<td><%= f.file_field :picture1 %></td>
<td><%= f.file_field :picture2 %></td>
<td><%= f.file_field :picture3 %></td>
<td><%= f.file_field :picture4 %></td>
<td><%= f.file_field :picture5 %></td>
<td><%= f.submit "ADD" %></td>
<td id="addimg"><button type="button" style="cursor:pointer;">Update</button></td>
</tr>
<% end %>
</table>

<table class="update-image">
<tr>
<th>1st image</th>
<th>2nd image</th>
<th>3rd image</th>
<th>4th image</th>
<th>5th image</th>
</tr>
<%= form_for :images,:url => {:action => "updateimage",:controller => "images" } do |f| %>
<tr>
<td><%= f.file_field :picture1 %></td>
<td><%= f.file_field :picture1 %></td>
<td><%= f.file_field :picture1 %></td>
<td><%= f.file_field :picture1 %></td>
<td><%= f.file_field :picture1 %></td>
</tr>
<% end %>
</table>


controller/images_controller.rb



class ImagesController < ApplicationController
def addimage
@admin=Admin.find(params[:admin_id])
@images=@admin.images.create(params[:images])
redirect_to :action => 'adminpage',:controller => 'posts'
end
def updateimage

end
end


routes.rb



Blogpost::Application.routes.draw do
root :to => "posts#index"
get "posts/login" => "posts#login"
get "posts/show" => "posts#show"
post "posts/logincreate" => "posts#logincreate"
get "posts/admin" => "posts#admin"
post "sessions/adminlogin" => "sessions#adminlogin"
get "posts/adminpage" => "posts#adminpage"
delete "posts/deluser" => "posts#deluser"
get "sessions/destroy" => "sessions#destroy"
get "posts/content" => "posts#content"
post "images/addimage" => "images#addimage"
post "images/updateimage" => "images#updateimage"
resources :posts do
resources :comments
end
end


images.rb



class Image < ActiveRecord::Base
belongs_to :admin
attr_accessible :picture1, :picture2, :picture3, :picture4, :picture5
mount_uploader :picture ,PictureUploader
end


admin.rb



class Admin < ActiveRecord::Base
attr_accessible :email, :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 :password, :confirmation => true
validates_length_of :password, :in => 6..20, :on => :create
has_many :images
end


db/migrate/20150220093517_create_images.rb



class CreateImages < ActiveRecord::Migration
def change
create_table :images do |t|
t.string :picture1
t.string :picture2
t.string :picture3
t.string :picture4
t.string :picture5
t.references :admin

t.timestamps
end
add_index :images, :admin_id
end
end


Please check the above codes and try to help me to store images in database via Admin model.Thanks in advance.


Cannot get delete request to work - rails

I have this route:



delete 'basket/remove' => 'flowercard_baskorder#remove', as: :basket_remove


This link in view:



<%= link_to "Remove", basket_remove_path %>


And this in my controller (the binding is just for me to test):



def remove
binding.pry

end


When the link is clicked on nothing happens and i have no idea why!? I'm obviosuly expecting the binding to kick in but doesn't even look like a request is made?


Cheers


Why do I get the error `undefined method 'map'`?

In my Ruby on Rails application I am trying to display a three drop down menus in the _form.html.erb which are rendered from the file _booking_lookup.html.erb and get there data from the drop down menu methods in the models.


_form.html.erb:



<%= render(:partial => '/booking_lookup', :locals=> {:film => @film = Film.all, :showings => @showings = Showing.all, :seats => @seats = Seat.all, :my_path => '/films/booking_lookup' }) %>


_booking_lookup.html.erb:



<%= form_tag my_path, :method=>'post', :multipart => true do %>
<%= select_tag ('title_id'),
options_from_collection_for_select(@films, :id, :title_info, 0 ),
:prompt => "Film" %>

<%= select_tag ('showings_id'),
options_from_collection_for_select(@showings, :id, :showing_times, 0 ),
:prompt => "Showings" %>

<%= select_tag ('seat_id'),
options_from_collection_for_select(@seats, :id, :seats_available, 0 ),
:prompt => "Seats" %>

<%= submit_tag 'Search' %>


film.rb:



class Film < ActiveRecord::Base

has_many :showings
belongs_to :certificate
belongs_to :category

def title_info
"#{title}"
end
end


seat.rb:



class Seat < ActiveRecord::Base
belongs_to :screen
has_many :bookings

def seats_available
"#{row_letter}#{row_number}"
end
end


showing.rb:



class Showing < ActiveRecord::Base
belongs_to :film
has_many :bookings
belongs_to :screen

def showing_times
"#{show_date.strftime("%e %b %Y")} @ #{show_time.strftime("%H:%M")}"
end
end


But for some reason with the line: <%= select_tag ('title_id'), options_from_collection_for_select(@films, :id, :title_info, 0 ), :prompt => "Film" %> I get the error:



NoMethodError in Bookings#new
undefined method `map' for nil:NilClass


The weird part is that I am using a lot of this code else where, I have a _multi_search.html.erb form:



<%= form_tag my_path, :method=>'post', :multipart => true do %>
<!-- Genre: -->
Search By:
<%= select_tag ('cat_id'),
options_from_collection_for_select(@categories, :id, :category_info, 0 ),
:prompt => "Genre" %>

<%= select_tag ('cert_id'),
options_from_collection_for_select(@certificates, :id, :certificate_info, 0 ),
:prompt => "Age Rating" %>

<%= text_field_tag :search_string, nil, placeholder: "ACTOR" %>
or
<%= select_tag ('title_id'),
options_from_collection_for_select(@films, :id, :title_info, 0 ),
:prompt => "Film" %>
<%= submit_tag 'Search' %>
<% end %>


And is used in the application.html.erb:


<%= render(:partial => '/multi_search', :locals=> {:categories => @categories = existing_genres, :certificates => @certificates = Certificate.all, :films => @films = Film.all, :my_path => '/films/multi_find' }) %>


And that works fine.


What am I doing wrong?