Friday, July 15, 2016

Ruby: gem devise | Fixed issues

Ruby: gem devise | Fixed issues


Ruby: gem devise

Posted: 15 Jul 2016 07:42 AM PDT

when I go to my http://localhost:3000/ I am getting the following:

ActiveRecord::PendingMigrationError

Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development

Extracted source:

# Raises <tt>ActiveRecord::PendingMigrationError</tt> error if any migrations are pending.  def check_pending!(connection = Base.connection)    raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?(connection)  end  def load_schema_if_pending!  

Also, when I tried to to the heroku run rake db:migrate in the console, it said:

StandardError: An error has occurred, this and all later migrations canceled: PG::DuplicateColumn: ERROR: column "email" of relation "users" already exists

I am new to ruby and followed the devise tutorial by Mackenzie Child. It's my last step to complete my first ruby application.

I am excited and looking forward to your help! :)

Sidekiq worker shutdown

Posted: 15 Jul 2016 07:39 AM PDT

I have got strange errors

2016-07-15T14:34:09.334Z 16484 TID-33ld0 WARN: Terminating 1 busy worker threads  2016-07-15T14:34:09.334Z 16484 TID-33ld0 WARN: Work still in progress [#<struct Sidekiq::BasicFetch::UnitOfWork queue="queue:load_xml", job="{\"class\":\"GuitarmaniaWorker\",\"args\":[],\"retry\":false,\"queue\":\"load_xml\",\"jid\":\"56c01b371c3ee077c2ccf440\",\"created_at\":1468590072.35382,\"enqueued_at\":1468590072.3539252}">]  2016-07-15T14:34:09.334Z 16484 TID-33ld0 DEBUG: Re-queueing terminated jobs  2016-07-15T14:34:09.335Z 16484 TID-33ld0 INFO: Pushed 1 jobs back to Redis  2016-07-15T14:34:09.336Z 16484 TID-33ld0 INFO: Bye!  

What can cause it?

Locally all work great but after deployment on production server this errors appeared.

Any suggestions.

rails 5 migration uninitialized constant

Posted: 15 Jul 2016 07:43 AM PDT

I have project on rails 4.2 with bunch of migrations. And on rails 4.2 everything works perfectly.

Now I created a new project on rails 5 and copied all my migrations from 4.2 project to new project.

When I try to run rails db:migrate, first 30 migrations run normal, then on 31, very simple migration, I have error:

uninitialized constant AddFactorToCurrencies::Currency

The file name is db/migrate/20160715140911_add_factor_to_currencies.rb

class AddFactorToCurrencies < ActiveRecord::Migration[5.0]    def up      add_column :currencies, :factor, :decimal, precision:18, scale:2, default:0, null: false      Currency.all.each do |c|        c.factor = 0        c.save      end    end      def down      remove_column :currencies, :factor    end  end  

Help me please.

Missing template layouts/mailer with {:locale=>[:en], :formats=>[:html],

Posted: 15 Jul 2016 07:36 AM PDT

I'm following michael harlt rails tutorial but i get this error

Missing template layouts/mailer with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in: * "/home/ubuntu/workspace/app/views"

when previewing account activation

This is my user_mailer.rb

class UserMailer < ApplicationMailer      def account_activation(user)      @user = user      mail to: user.email,  subject: "Account activation"    end      def password_reset      @greeting = "Hi"        mail to: "to@example.org"    end  end  

and the error highlights the line that says

mail to: user.email,  subject: "Account activation"  

I tried adding layout 'mailer' in user_mailer.rb but it doesn't work.

How to pull a parameter into a string in rails

Posted: 15 Jul 2016 07:25 AM PDT

ERROR: syntax error, unexpected tIDENTIFIER, expecting ')' ...endMail?email_to=#{'appointment.email'} syntax error, unexpected ')', expecting keyword_end ...check+the+website+for+details').read ... ^ I want to pull a parameter into a string in Rails.

require 'open-uri'  response = open('http://mqttxy.mybluemix.net/sendMail?email_to=#   {'@appointment.email'}&from=abc@gmail.com&subject=New+Appointment&message  =Please+check+the+website+for+details').read  

'let' not memoize values in rsepc

Posted: 15 Jul 2016 07:14 AM PDT

I have a user model, who have a many-to-many relationship whit itself: user A add user B as a friend, and automatically, user B becomes friend of user A too.

Performing the following steps in the rails console:

1) Create two users and save them:

2.3.1 :002 > u1 = User.new(name: "u1", email: "u1@mail.com")   => #<User _id: 5788eae90640fd10cc85f291, created_at: nil, updated_at: nil, friend_ids: nil, name: "u1", email: "u1@mail.com">   2.3.1 :003 > u1.save   => true   2.3.1 :004 > u2 = User.new(name: "u2", email: "u2@mail.com")   => #<User _id: 5788eaf80640fd10cc85f292, created_at: nil, updated_at: nil, friend_ids: nil, name: "u2", email: "u2@mail.com">   2.3.1 :005 > u2.save   => true   

2) Add user u2 as friend of u1:

2.3.1 :006 > u1.add_friend u2   => [#<User _id: 5788eaf80640fd10cc85f292, created_at: 2016-07-15 13:54:04 UTC, updated_at: 2016-07-15 13:55:19 UTC, friend_ids: [BSON::ObjectId('5788eae90640fd10cc85f291')], name: "u2", email: "u2@mail.com">]   

3) Check their friendship:

2.3.1 :007 > u1.friend? u2   => true   2.3.1 :008 > u2.friend? u1   => true   

As we can see, the "mutual friendship" works. But in my tests that doesn't happen. Here are my tests:

require 'rails_helper'    RSpec.describe User, type: :model do        let(:user) { create(:user) }    let(:other_user) { create(:user) }      context "when add a friend" do      it "should put him in friend's list" do        user.add_friend(other_user)        expect(user.friend? other_user).to be_truthy      end        it "should create a friendship" do        expect(other_user.friend? user).to be_truthy      end    end  end  

Here are the tests result:

Failed examples:    rspec ./spec/models/user_spec.rb:33 # User when add a friend should create a friendship  

The only reason that I can see to the second test is failing is because my let is not memoizing the association to use in other tests. What am I doing wrong?

Here is my User model, for reference:

class User    include Mongoid::Document    include Mongoid::Timestamps      has_many :posts    has_and_belongs_to_many :friends, class_name: "User",                             inverse_of: :friends, dependent: :nullify      field :name, type: String    field :email, type: String      validates :name, presence: true    validates :email, presence: true      index({ email: 1 })      def friend?(user)      friends.include?(user)    end      def add_friend(user)      friends << user    end      def remove_friend(user)      friends.delete(user)    end  end  

Rails DB error when trying to include associated model to JSON response

Posted: 15 Jul 2016 07:04 AM PDT

I'm trying to build a messaging system through an API using Rails 4.

Models:

class User < ActiveRecord::Base   has_many :sent_messages, class_name: "Message", foreign_key: "sender_id"   has_many :received_messages, class_name: "Message", foreign_key: "recipient_id"  end    class Message < ActiveRecord::Base   belongs_to :sender, class_name: "User", primary_key: "sender_id"   belongs_to :recipient, class_name: "User", primary_key: "recipient_id"  end  

Migrations:

class DeviseTokenAuthCreateUsers < ActiveRecord::Migration   def change    create_table(:users) do |t|       ...       ## User Info     t.string :name       ...      end   end  end  

and

class CreateMessages < ActiveRecord::Migration   def change    create_table :messages do |t|        t.string :msg_body        t.belongs_to :sender, class_name: "User", primary_key: "sender_id", index: true      t.belongs_to :recipient, class_name: "User", primary_key: "recipient_id", index: true      t.timestamps null: false    end   end  end  

Message Controller:

class MessagesController < ApplicationController     def index    messages = Message.all    render :json => messages.as_json(:include => [:sender, :recipient])   end    end  

PROBLEM

The thing is, when I go for a GET request of all the messages, I get this error:

ActiveRecord::StatementInvalid (SQLite3::SQLException: no such column: users.sender_id: SELECT  "users".* FROM "users" WHERE "users"."sender_id" = ? LIMIT 1)  

So, what am I doing wrong? Why? What can I do about this?

Words including given string in Ruby

Posted: 15 Jul 2016 07:21 AM PDT

I'm writing little Rails api application, and I need to analyze string to find words having given string like:

Assuming my source text is hello mr one two three four nine nineteen and I want to check occurence of on, it will produce: one, and if I'll check occurence of ne t in the same string it will result in one two.

I know there is an ugly way with substrings, counting positions and parsing string this way, but I think it can be solved with regex scan.

Please say if you need some additional information, thanks.

How to use Ruby's send method without receiver?

Posted: 15 Jul 2016 06:34 AM PDT

I am trying to convert user input à la "6 months" into a Ruby method à la 6.months.

How can this be done?

I keep getting an undefined method 6.months error in line 10.

Thanks for any help.

class Coupon < ActiveRecord::Base      def self.duration_options      ["3 years", "2 years", "1 year", "6 months", "3 months", "1 month"]    end      def end_at      if Coupon.duration_options.include?(duration)        method = duration.sub!(' ', '.')        time = Time.zone.now + send(method)      end      time    end    end  

To display time spent by user on all tasks daily

Posted: 15 Jul 2016 06:42 AM PDT

I want to display how much time a single user spends on all tasks in a day.

Currently I'm using this query to display the time spent by all the users on all tasks daily:

TaskTimeTracker.group("year(created_at)").group("month(created_at)").group("day(created_at)").sum("time_spent")  

These are the Schema Information of models I have used.

#Table name: tasks    #id              :integer          not null, primary key  #name            :string(255)  #description     :text(65535)  #due_date        :string(255)  #status          :integer  #priority        :integer  #project_id      :integer  #user_id         :integer  #created_at      :datetime         not null  #updated_at      :datetime         not null  #estimated_time  :datetime  #start_time      :datetime  #completion_time :datetime  #parent_task_id  :integer  #task_type       :string(255)  #author_id       :integer  #slug            :string(255)    #Indexes    #index_tasks_on_project_id  (project_id)  #index_tasks_on_slug        (slug) UNIQUE  #index_tasks_on_user_id     (user_id)    #Table name: task_time_trackers    #id          :integer          not null, primary key  #description :text(65535)  #time_spent  :float(24)  #created_at  :datetime         not null  #updated_at  :datetime         not null  #task_id     :integer  #created_by  :string(255)    #Indexes    #index_task_time_trackers_on_task_id  (task_id)      class TaskTimeTracker < ActiveRecord::Base      belongs_to :task      validates :description,presence:true      validates :time_spent,presence:true  end    class Task < ActiveRecord::Base    include PublicActivity::Model    attr_accessor :estimated_time_field, :prev_user_id    validate :due_date_validation      extend FriendlyId    friendly_id :task_type, use: [:slugged,:finders]      belongs_to :project    belongs_to :user    has_many :worked_tasks, dependent: :destroy    has_many :comments, dependent: :destroy    has_many :logs, dependent: :destroy    has_and_belongs_to_many :tags      has_many :subtasks, class_name: "Task", :foreign_key => :parent_task_id    belongs_to :parent_task, class_name: "Task"     has_many :task_time_trackers, dependent: :destroy  end  

Can a ruby class method inherit from another class?

Posted: 15 Jul 2016 06:10 AM PDT

I read here that a ruby class can only inherit from one class, and can include modules.

However, the devise module defines controllers like this:

class Users::PasswordsController < Devise::PasswordsController    ...  end  

Now, given that Users is probably a class, with PasswordsController being a method:

>> Devise::PasswordsController.class  => Class  

How is it that a method in a class inherits from another class?

DatePickerRange set 30 days default time difference

Posted: 15 Jul 2016 05:53 AM PDT

I am trying to have a preset data difference when you select the start date. It should be always 30days difference between start n end date either one you choose.

I am using the following plugin. But not able to get it to work.

<input name='campaign[date_range]' value='<%= @campaign.date_range %>' ui-jq="daterangepicker" ui-options="{                            format: 'DD-MM-YYYY',                            minDate: '<%= DateTime.tomorrow.strftime("%d-%m-%Y") %>',                            maxDate: '<%= (DateTime.tomorrow + 90).strftime("%d-%m-%Y") %>',                              <% if @campaign.start_date.present? %>                              startDate: '<%= @campaign.start_date.strftime("%d-%m-%Y %l:%M %p") %>',                            <% else %>                              startDate: '<%= DateTime.tomorrow.strftime("%d-%m-%Y") %>',                            <% end %>                              <% if @campaign.end_date.present? %>                              endDate: '<%= @campaign.end_date.strftime("%d-%m-%Y %l:%M %p") %>',                            <% else %>                              endDate: '<%= (DateTime.tomorrow + 30).strftime("%d-%m-%Y") %>',                            <% end %>                              drops: 'up'                            }" class="form-control w-md" />  

make the post index page as root path

Posted: 15 Jul 2016 05:46 AM PDT

I want to make the post index page the root page and also get the /posts to redirect to the root path as well the prefix of the index is posts... I try this one in the routes(but i dont know if it is the right way)

root "posts#index'  resources :posts, except: [:index]  

so now i get the root for index but the /posts not working ... instead of getting the error i want it to redirect to the root page... here is my posts routes after changing my routes file...

 root GET    /                              posts#index                 posts POST   /posts(.:format)               posts#create              new_post GET    /posts/new(.:format)           posts#new             edit_post GET    /posts/:id/edit(.:format)      posts#edit                  post GET    /posts/:id(.:format)           posts#show                       PATCH  /posts/:id(.:format)           posts#update                       PUT    /posts/:id(.:format)           posts#update                       DELETE /posts/:id(.:format)           posts#destroy  

How to generate HTML Test Report with Test Unit - Ruby?

Posted: 15 Jul 2016 05:38 AM PDT

I have a simple project, developed on test::unit framework with Ruby. It is working fine. Now I want to generate an HTML test report of the tests I executed with passed/failed status and other relative data. I have three files

(1) Rakefile (to call runner.rb file) as following:

task :default => :TestRunner      desc "run suite test"      task :TestRunner  do        ruby "D:/TestUnit/runner.rb"      end  

(2) runner.rb (to execute test suite) as following:

base_dir = File.expand_path(File.join(File.dirname(__FILE__), ".."))  test_dir = File.join(base_dir, "testUnit/suite.rb")    require 'test/unit'    exit Test::Unit::AutoRunner.run(true, test_dir)  

(3) suite.rb (contains all the tests) as following:

gem "test-unit"  require "test/unit"    class Test1< Test::Unit::TestCase  description "Test Case for adding two values..!!", :test_add  description "Test Case for subtracting two values..!!", :test_sub      def setup      puts "running the setup........."      @number1 = 4      @number2 = 2        end    def test_add      puts "asserting the add function: " + description      numb1=@number1+@number2      assert_equal(7, numb1 + 1, "added correctly")    end      def test_sub      puts "asserting the subtract function: " + description      numb2=@number1-@number2       assert_equal(2, numb2 - 0, "subtracted correctly")    end      def teardown      puts "running teardown......."      @number = nil       end  end  

Please point me to the right direction what else I need to do to generate an HTML test report. I am a beginner in Ruby.

Problems with select tag logic rails

Posted: 15 Jul 2016 06:12 AM PDT

I have a SoldHistory model that belongs to a Product model and also have a Branch model. In the product show page theres a form to create SoldHistory sold:integer attribute. I am trying to add a select tag to the form that will pick objects from the Branch model.

<%= form_for [@product, @product.sold_histories.build, @branch = Branch.find(:all)] do |f| %>      <%= f.label "Dispatch: "%>      <%= f.number_field :sold %>      <%= f.select :branch, options_from_collection_for_select(@branch, "id", "name") %>      <%= f.submit "Enter" %>    <% end %>  

I tried this but it keeps saying could not find branch with id=all

Please what am I doing wrong?

Rails 4 app with devise and mailgun on heroku does not send confirmation but resends it

Posted: 15 Jul 2016 05:18 AM PDT

My rails 4 app on heroku in production uses mailgun addon for sending mail. It does not send confirmation emails, but sends reconfirmations (when I click on "didn't receive confirmation instructions" on the sign up page. This was working a few weeks back, but it is not working now.

I have checked the configuration is correct in my production.rb (and it is obviously correct because resend is also using the same - mailgun - addin).

I have seen other threads that talk about similar issues, and fixed some of the issues in production based on this (like replacing the heroku env vars with the domain instead of default sandbox params). But still no dice. The reconfirmation email appears in the logs, but the confirmation email does not. Here are the heroku logs for the new user creation - notice the conspicuous absence of the email being sent. Also note that confirmation_sent_at is already set on the user:

2016-07-15T11:51:37.136775+00:00 app[web.1]: Processing by Devise::RegistrationsController#create as HTML  2016-07-15T11:51:37.136837+00:00 app[web.1]:   Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "user"=>{"name"=>"someuser", "email"=>"someuser@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "remember_me"=>"1", "terms"=>"1"}, "commit"=>"Sign up"}  2016-07-15T11:51:37.215840+00:00 app[web.1]:    (0.8ms)  BEGIN  2016-07-15T11:51:37.221482+00:00 app[web.1]:    (0.9ms)  SELECT COUNT(*) FROM "users" WHERE "users"."provider" = $1 AND "users"."email" = $2  [["provider", "email"], ["email", "someuser@gmail.com"]]  2016-07-15T11:51:37.223444+00:00 app[web.1]:   User Load (0.9ms)  SELECT "users".* FROM "users" WHERE (lower(name) = 'someuser')  2016-07-15T11:51:37.225376+00:00 app[web.1]:    (0.7ms)  SELECT COUNT(*) FROM "users" WHERE (lower(email) = 'someuser')  2016-07-15T11:51:37.523683+00:00 heroku[router]: at=info method=POST path="/users" host=www.example.com request_id=some-request-id fwd="106.51.29.78" dyno=web.1 connect=0ms service=362ms status=302 bytes=1116  2016-07-15T11:51:37.471475+00:00 app[web.1]:   User Load (1.1ms)  SELECT  "users".* FROM "users" WHERE "users"."confirmation_token" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["confirmation_token", "<some_confirmation_token>"]]  2016-07-15T11:51:37.479471+00:00 app[web.1]:   SQL (1.4ms)  INSERT INTO "users" ("email", "encrypted_password", "name", "tokens", "uid", "created_at", "updated_at", "confirmation_token", "confirmation_sent_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING "id"  [["email", "someuser@gmail.com"], ["encrypted_password", "..."], ["name", "someuser"], ["tokens", "{}"], ["uid", "someuser@gmail.com"], ["created_at", "2016-07-15 11:51:37.226192"], ["updated_at", "2016-07-15 11:51:37.226192"], ["confirmation_token", "..."], ["confirmation_sent_at", "2016-07-15 11:51:37.472233"]]  2016-07-15T11:51:37.482940+00:00 app[web.1]:    (2.3ms)  COMMIT  2016-07-15T11:51:37.487766+00:00 app[web.1]: Redirected to http://www.example.com/  

css background image not loading in heroku

Posted: 15 Jul 2016 05:12 AM PDT

I have a problem that I'm facing. I tried many times to solve it following stackoveflow but no succes. the css image is loading on local machine but not on heroku.

style.css.sccs file:

#header-section {      background-image: asset-data-url("Benz-E-Class.jpg");          background-repeat:no-repeat          center top;      margin-top: -20px;      padding-top:20px;      text-align:center;      background-position: center center;      min-height: 700px;      width: 100%;          -webkit-background-size: 100%;      -moz-background-size: 100%;      -o-background-size: 100%;      background-size: 100%;      -webkit-background-size: cover;      -moz-background-size: cover;      -o-background-size: cover;      background-size: cover;  }  

on production.rb:

 config.cache_classes = true   config.serve_static_assets = true   config.assets.compile = true   config.assets.digest = true  

I executed:

RAILS_ENV=production rake assets:precompile  

gem file:

source 'https://rubygems.org'  ruby "2.2.3"         # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '4.2.6'  # Use sqlite3 as the database for Active Record  #gem 'sqlite3'  # Use SCSS for stylesheets  gem 'sass-rails', '~> 5.0'  # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'  # Use CoffeeScript for .coffee assets and views  gem 'coffee-rails', '~> 4.1.0'  # See https://github.com/rails/execjs#readme for more supported runtimes  # gem 'therubyracer', platforms: :ruby    # Use jquery as the JavaScript library  gem 'jquery-rails'  # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks  gem 'turbolinks'  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder  gem 'jbuilder', '~> 2.0'  # bundle exec rake doc:rails generates the API under doc/api.  gem 'sdoc', '~> 0.4.0', group: :doc    # Use ActiveModel has_secure_password  # gem 'bcrypt', '~> 3.1.7'    # Use Unicorn as the app server  # gem 'unicorn'    # Use Capistrano for deployment  # gem 'capistrano-rails', group: :development    gem 'font-awesome-rails', '~> 4.1.0.0'    group :development, :test do    # Call 'byebug' anywhere in the code to stop execution and get a debugger console      gem 'sqlite3', '1.3.9'    gem 'byebug', '3.4.0'    end    group :development do    # Access an IRB console on exception pages or by using <%= console %> in views    gem 'web-console', '~> 2.0'      # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring    gem 'spring'  end    group :production do    gem 'pg', '0.17.1'    gem 'rails_12factor', '0.0.2'    gem 'puma', '2.11.1'  end  

Thank you!

Apply Sorting to all the fields in Html table with mongoid database and kaminari gem

Posted: 15 Jul 2016 05:12 AM PDT

How to do sorting for every field in html table, Iam using mongoid and Kaminari for pagination.

Limit association based on rich relation attributes

Posted: 15 Jul 2016 06:02 AM PDT

first question for me here! Im trying to assign 'key companies' to my users. These are found in a many-to-many rich join table. On this table there are attributes like new, key, active and so forth. I want to assign companies to users in a long list and for that Im using SimpleForm.

Everything is working excepts that I want to filter out and limit the association relation based on the attributes on the rich relation. I have company relations for each user but not all of them are akey-relation or a new-relation for example. I only want the association being key to show up and not touch the other ones. I also want to set the attribute active to true when Im assigning these companies to the users. My code looks like this now:

user.rb

class User < ActiveRecord::Base      has_many :company_user_relationships      has_many :companies, through: :company_user_relationships  

company.rb

class Company < ActiveRecord::Base      has_many :company_user_relationships      has_many :users, through: :company_user_relationships  

schema.rb

create_table "company_user_relationships", force: true do |t|    t.integer  "company_id"    t.integer  "user_id"    t.boolean  "key"    t.boolean  "active"    t.datetime "last_contacted"    t.string   "status_comment"    t.datetime "created_at"    t.datetime "updated_at"    t.integer  "status"    t.boolean  "new"  end  

users_controller.rb

def assign_key_companies      User.update(params[:users].keys, params[:users].values)      redirect_to(:back)  end  

view

= form_for :user_companies,          url: assign_key_companies_users_path,          html: {:method => :put} do |f|    - users.each do |user|      = simple_fields_for "users[]", user do |u|        tr          td.col-md-4            = "#{user.first_name} #{user.last_name}"          td.col-md-8            = u.association :companies, label: false, collection: @key_company_candidates,                        input_html: {data: {placeholder: " Assign key companies"}, class: 'chosen-select'}    = submit_tag "Save key companies", class: "btn btn-success pull-right"  

I basically want to only show user.companies.where(key: true) and the SQLCOMMIT to always put the key-field to true when updating the record.

How can i filter out to only affect the associations I want?

Mail not sending from ewebguru domain Rails

Posted: 15 Jul 2016 04:22 AM PDT

I have a domain techo.com (bought from ewebguru) and I'm tryng to send mail from my rails app but mail is not sending I'm using following code configuration in production and development :

{    :user => 'abcd@techo.com',    :password => '*********',    :domain => 'techo.com',    :port => 25,    :authentication => :none   }  

somebody suggest me to do these :

User: mail id  Password: mail id password  SMTP Server: tecorb.com  SMTP Port: 25  POP Port: 110  SSL Authentication:None  

I'm not getting how to configure these into my development.

Please suggest me.

Omnicontacts redirect_uri: facebook, hotmail, yahoo

Posted: 15 Jul 2016 04:21 AM PDT

I am using the omnicontacts gem so that users can invite their contacts on my website. I have set it up successfully for Google.

I have setup an omnicontacts controller with the contacts_callback method as suggested by the gem's readme.

and a route: get "/contacts/:importer/callback" => "omnicontacts#contacts_callback"

At the initializer of omnicontacts.rb I have the followings:

require "omnicontacts"    Rails.application.middleware.use OmniContacts::Builder do    importer :gmail, "hidden-client-key", "hidden-secret-key", {redirect_path: "/contacts/gmail/callback"}  importer :facebook, "hidden-client-key", "hidden-secret-key", {:redirect_path => "/contacts/facebook/callback" }  importer :hotmail, "hidden-client-key", "hidden-secret-key", {redirect_path: "/contacts/hotmail/callback"}  end  

The last two (facebook and hotmail) according to the gem's readme file do not need a redirect_path but just in case I tested both with it or not and I still get an error that the redirect_uri is invalid. As I was searching for a solution I found a place that the :redirect_path was instead :callback_path and tried that as well but no luck.

On the Microsoft app (for hotmail) I was getting a longer description on the error which was:

The provided value for the input parameter 'redirect_uri' is not valid. The expected value is 'https://login.live.com/oauth20_desktop.srf' or a URL which matches the redirect URI registered for this client application.

As a result I went on and registered a redirect URI for this client application. The URI was http://example.com/contacts/hotmail/callback which matches the callback path.

Still, getting the same error. Any clue?

break if method takes more than 30sec time to execute

Posted: 15 Jul 2016 04:51 AM PDT

I benchmarked the execution time for method

tests.each do |test|    time = Benchmark.realtime { method(test) }  end    def method(test)     code  end  

Which is returning time in seconds

But what I want is to break the loop if this method is taking more than 30 sec of execution time.

suggest a clean way to do it.

Remove brackets around an array in ruby

Posted: 15 Jul 2016 04:47 AM PDT

Lets say I have an array

array = ["Hii", "Hello", "Bye"]  

I want to show the array in following format

"Hii","Hello","Bye"  

What would be the best way to do it?

[SOLVED]How to change the path for edit user from edit_user to account_settings?

Posted: 15 Jul 2016 04:11 AM PDT

The default path for editing user is edit_user_path. Is it possible to customize the path so that it will become account_settings_path?

I already did the same for user sign up. Instead of the default new_user_path, I was able to changed it to signup_path.

But the edit user is different because the URI Pattern in rails routes is /users/:id/edit so I'm confused what code to write in routes.rb unlike the signup_path where I can just write the codes:

get  '/signup', to: 'users#new'  post '/signup', to: 'users#create'  

which adds a new routes in rails routes to signup.

edit: I solved it already using the code:

get '/users/:id/account_settings', to: 'users#edit', as: 'account_settings'  

Rails - bookings not saving to database

Posted: 15 Jul 2016 03:39 AM PDT

I'm building an Event site using Rails. When creating an event the user is able to offer both paid and free events. It appears that a booking_id is being allocated only to paid events not for free events. I've checked my console and this is definitely the case. This is obviously causing issues and I'm not quite sure how to resolve.

Here's my code -

bookings_controller.rb

class BookingsController < ApplicationController    before_action :authenticate_user!    def new      # booking form      # I need to find the event that we're making a booking on      @event = Event.find(params[:event_id])      # and because the event "has_many :bookings"      @booking = @event.bookings.new      # which person is booking the event?      @booking.user = current_user      @booking.quantity = @booking.quantity      @total_amount = @booking_quantity.to_f * @event_price.to_f    end    def create      # actually process the booking      @event = Event.find(params[:event_id])      @booking = @event.bookings.new(booking_params)      @booking.user = current_user      #@total_amount = @booking.quantity.to_f * @event.price.to_f        Booking.transaction do          @booking.save!          @event.reload          if @event.bookings.count > @event.number_of_spaces          flash[:warning] = "Sorry, this event is fully booked."          raise ActiveRecord::Rollback, "event is fully booked"          end       end              if @booking.save            # CHARGE THE USER WHO'S BOOKED          # #{} == puts a variable into a string          Stripe::Charge.create(amount: @event.price_pennies, currency: "gbp",              card: @booking.stripe_token, description: "Booking number #{@booking.id}")            flash[:success] = "Your place on our event has been booked"          redirect_to event_path(@event)      else          flash[:error] = "Payment unsuccessful"          render "new"      end        if @event.is_free?            @booking.save!          flash[:success] = "Your place on our event has been booked"          redirect_to event_path(@event)      end  end      private    def booking_params      params.require(:booking).permit(:stripe_token, :quantity)  end        end  

Booking table -

create_table "bookings", force: :cascade do |t|  t.integer  "event_id"  t.integer  "user_id"  t.string   "stripe_token"  t.datetime "created_at",   null: false  t.datetime "updated_at",   null: false  t.integer  "quantity"    end  

I've added @booking.save! into the create method for free events but no change. I've also added the transaction code block in order to avoid over-booking but this only works for paid events. Any assistance, appreciated.

Rails configure application to have url prefix

Posted: 15 Jul 2016 05:14 AM PDT

I feel like this should not be all that difficult, but I cannot find any solutions that seem to work with Rails4

My setup

  • I have a proxy server (Kong) that directs to various services behind it based on path.
    • myapp.com/app1/ is redirected to http://app1_address:PORT/ (notice /app1 is stripped)
    • same for myapp.com/app2

app2 is a Rails 4 application and it works just fine when browsing to specific, but its relative routing is completely off. For example, link_to or url_for links to controllers or actions all redirect to the wrong links.

For example, I have a logout link that has a path of /logout on app2, but redirecting the user to /logout is incorrect. They need to be routed to /app2/logout. How can I configure the Rails app to add a prefix to all routes?

I have tried:

config.action_controller.relative_url_root = '/app2'  

As well as this:

config.relative_url_root = '/app2'  

And this in config.ru

map <MyAppName>::Application.config.relative_url_root || "/" do    run Rails.application  end  

Any ideas for how to make this work?

How to make my project choose rbenv version of ruby

Posted: 15 Jul 2016 03:38 AM PDT

I am planning to run ruby 2.3.1 version with Rails 5 on Mac OSX.

1 I installed rbenv then install ruby version 2.3.1.

rbenv version  2.3.1 (set by /D/testProject/.ruby-version)  

2 Update gem

gem update --system  Latest version currently installed. Aborting.  

3 System ruby version:

ruby -v  ruby 2.0.0p648 (2015-12-16 revision 53162) [universal.x86_64-darwin15]  

But when i run gem update rails, i got

ERROR:  Error installing rails:      activesupport requires Ruby version >= 2.2.2.  

So my question is how to make the project choose rbenv version of ruby? Then i can update to Rails 5.

EDIT

I have ran rbenv local 2.3.1 (.ruby-version was created) already. But still can't update to Rails5 Thank you!

How to have a select_tag with an "selected disabled hidden" option?

Posted: 15 Jul 2016 05:04 AM PDT

I want to have a select_tag that includes a field which displays "Please select" to the user. This field must not be selectable by the user.

Here is a jsfiddle of what I want to have : http://jsfiddle.net/gleezer/pm7cefvg/1/

In Rails, I tried to do this :

  <%= select_tag(:userchief, options_for_select(@options_for_selectUsers, {:selected => "x1", :disabled => "x1", :hidden => "x1"})) %>  

(@options_for_user is an array which contains multiple key/value elements) But when I check the source code of my page, I can see this for my option :

<option disabled="disabled" selected="selected" value="x1">Select</option>  

That is not what I want to have, the x1 select option appears in the dropdown menu of the select because the hidden field is not present.

How can I do to obtain the same result as I can see in the jsfiddle link ?

Should I use different models for authentication

Posted: 15 Jul 2016 03:24 AM PDT

I have a rails project which is going to have two types of users - Staff and Parents.

In general, the website will have two different sections where parents can view student details and another where staff can update student details.

A staff may however also be a parent.

What would the best strategy in this case be -

  1. Seperate model for Staff and Parents
  2. Single user model with an is_staff and is_parents fields to separate the two

How can i point a rails model to json file instead of creating a table

Posted: 15 Jul 2016 05:25 AM PDT

I have a Rails application and a JSON file which contains the data, instead of creating table for a model i want to point my model to read that jSON file, and i should be table to treat that file like a table, please suggest.

No comments:

Post a Comment