Monday, July 18, 2016

How to recover an user account with a specific email address in Ruby ( User Devise Gem use ) | Fixed issues

How to recover an user account with a specific email address in Ruby ( User Devise Gem use ) | Fixed issues


How to recover an user account with a specific email address in Ruby ( User Devise Gem use )

Posted: 18 Jul 2016 08:30 AM PDT

I'm here to ask how to recover an user account that happened to be deleted ( as a mistake ). The user's email address was 'sungpah+100@gmail.com' for instance and want to use this email address again as an account.

I tried to make a new user and insert the same email address but the console output is

User Exists (1.4ms) SELECT 1 AS one FROM users WHERE users.email = BINARY 'sungpah+100@gmail.com' LIMIT 1 (1.1ms) ROLLBACK

Can I make an account with 'sungpah+100@gmail.com' again?

When I tried to search the account with the command : User.find_by(:email => 'sungpah+1@gmail.com', the result is nil currently!

The id was 950 and now if I search with User.find(950), ActiveRecord::RecordNotFound: Couldn't find User with 'id'=950 [WHERE users.deleted_at IS NULL] is the outcome!

Looking forward to seeing any response! Best

Devise in Rails Engines

Posted: 18 Jul 2016 08:24 AM PDT

I'm quite new to rails, and especially engines; where is the gemspec where I can add in

Gem::Specification.new do |s|    s.add_dependency "devise"  end  

as per devise documentation?

https://github.com/plataformatec/devise/wiki/How-To:-Use-devise-inside-a-mountable-engine

I have tried going to the engine.rb, rapidfire.rb but to no avail... requiring 'devise' in engine.rb doesn't work as some other posts have said :(

Rails blog tutorial 4.3 ProgramError

Posted: 18 Jul 2016 08:23 AM PDT

I'm attempting to follow the rails tutorial for creating a blog here. I'm on step 4.3, but after adding root 'welcome#index' to my roots.rb file, I get an error page telling me this:

TypeError: Object doesn't support this property or method  

Photo of error

RSpec Couldn't find with 'id'=

Posted: 18 Jul 2016 08:20 AM PDT

I'm writing an RSpec controller test and I've run into the following problem.

The relationship is such that Invoices belong to a Purchase, and a Purchase has many invoices.

My controller has:

class InvoicesController < ApplicationController    def index      @invoices = Invoice.all    end      def new      @purchase = Purchase.find(params[:purchase])      @invoice = Invoice.new(:purchase_id => params[:purchase])    end  

My factory has:

FactoryGirl.define do    factory :invoice do |f|      sequence(:id) { |number| number }      f.purchase_id {rand(1..30)}      f.number { FFaker::String.from_regexp(/\A[A-Za-z0-9]+\z/) }      f.terms { FFaker::String.from_regexp(/\A[A-Za-z0-9\s]+\z/) }      f.currency { FFaker::String.from_regexp(/\A[A-Z]+\z/) }      f.total_due {'25000.00'}      f.current_balance {'12500.00'}      f.due_date { FFaker::Time.date }      f.notes { FFaker::HipsterIpsum.paragraph }      f.status {[:open, :paid, :canceled].sample}      purchase    end      factory :invalid_invoice, parent: :invoice do |f|      f.status nil    end  end  

My controller spec (just the problematic part) has:

describe "GET new" do      it "assigns a new invoice to @invoice" do        invoice = FactoryGirl.create(:invoice)        get :new        expect(assigns(:invoice)).to_not eq(invoice)      end        it "renders the :new template" do        get :new        expect(response).to render_template :new      end    end  

When I run the test I get this:

1) InvoicesController GET new assigns a new invoice to @invoice       Failure/Error: get :new       ActiveRecord::RecordNotFound:         Couldn't find Purchase with 'id'=       # ./app/controllers/invoices_controller.rb:7:in `new'       # ./spec/controllers/invoices_controller_spec.rb:38:in `block (3 levels) in <top (required)>'      2) InvoicesController GET new renders the :new template       Failure/Error: get :new       ActiveRecord::RecordNotFound:         Couldn't find Purchase with 'id'=       # ./app/controllers/invoices_controller.rb:7:in `new'       # ./spec/controllers/invoices_controller_spec.rb:43:in `block (3 levels) in <top (required)>'  

My guess is that the params[:purchase] is the problem. How can I get the test to pass?

How to parse incoming JSON from my controller?

Posted: 18 Jul 2016 08:29 AM PDT

I am JSON posting the following JSON to my controller:

{"user_id": 234324, "user_action": 2, "updated_email": "asdf@asdf.com" }  

In my controller I can see the JSON is correctly POSTED but I am not sure how to access it:

def update_email    puts request.body.read.html_safe      user_id = params[:user_id]    user = User.find(user_id)  end  

I am testing this in my controller_spec and currently it is throwing an exception and is showing the id is empty.

how can i get date of every 7th day from start date for a period of time

Posted: 18 Jul 2016 07:47 AM PDT

how can i get date of every 7th day from start date for a period of time.

I have a scheduler that is supposed to run at every 7 days after its start datetime is set to send push notification for every time zone.

eg.

   start_time              run_every          end_time  20-july-2016 10:00:00      7_days       25-dec-2016 10:00:00  

then i will run scheduler every 7 days from 20-july-2016 at 10 am. that will be 28-july, 4-aug, 11-aug and so on.

The problem is its supposed to be run for all time zones so that user in australia can get notification on 20-july-2016 10:00:00 and user in US should also get notification on 20-july-2016 10:00:00.

for that I am running scheduler on start_date, start_date+1.days, start_date-1.days because my server is in UTC timezone so that it can occupy 10 am of every timezone.

I cant figure out a way to run it in intervals of 7 days. how can i get next running dates and check every day that should i run this notification today?

Test_helper for a loop in the view in Ruby gem

Posted: 18 Jul 2016 08:22 AM PDT

This code loops through and prints the entire hash, but if the size of the hash is greater than 4MB, it iterates over the first ten elements only.

<% sections_content.each do |title, summary| %>      <tr>        <td style="border-bottom: 1px solid #eeeeee;"><%= raw title %></td>      </tr>      <tr>        <td><%= raw summary %></td>      </tr>      <% break if ObjectSpace.memsize_of(sections_content) > 4194304 && index == 9 %>  <% end %>  

I want to write a test for it to ensure the loop breaks when the index is equal to 9, which means it loops over the first ten elements.

I'm thinking of something like this:

require 'test_helper'  test "should size> 400" do    assert_equal(9, index, [msg])  end  

The test doesn't work. Any help for a better method to test this code [sic]

Confusion on one_to_many relationships Rails

Posted: 18 Jul 2016 07:44 AM PDT

I am confused about how to assign multiple tags to one menu item.

If I have a new Menu Item named 'Tacos', I want this menu item to have the tags 'Spicy' and 'Protein' assigned to it.

Similarly, if I have a new Menu Item named 'Steak', I want to apply the same 'Protein' tag to this item. Is this possible?

class MenuTag < ActiveRecord::Base    belongs_to :menu_item  end    class MenuItem < ActiveRecord::Base    has_many :menu_tags  end    food_one = MenuItem.new(name: "Tacos", tags: NOT SURE WHAT GOES HERE???)  food_two = MenuItem.new(name: "Steak", tags: NOT SURE WHAT GOES HERE???)    spicy = MenuTag.new(name: "Spicy", menu_item_id: 1)  protein = MenuTag.new(name: "Protein, menu_item_id: 1,2) <---- can I assign two id's here???  

Global array for ruby on rails

Posted: 18 Jul 2016 07:41 AM PDT

I want to include an array which stocks the information of a model. Whenever an object of model A is created, the attribute name of this object is added in the array and this array won't be re-set when I restart the server. I try put the array to the associated model class and controller, but it does not work. Can you tell me how to do this?

Report service pdf, trouble displaying proper information.

Posted: 18 Jul 2016 07:17 AM PDT

I am working on a project in which I have some information that I need to have displayed on a pdf. The file i'm working with is a service file through a rails app. The problem that I am having is that within this pdf service throughout the page i've been able to pull information from my database and have it displayed, however the true problem is that I need to loop through specific information within the database, and then further map through specific information.

Throughout the pdf service when I need to display information I do it through this.

"".tap do |html|    @report.information.each do |information|    html << "<div>#{information}</div>"  

This works well for me and displays the proper information that I need. However I'm stuck when I need to displayed more detailed information where I have to do a little bit of manipulation to pull up the data, and its making my method of displaying it tricky.

"".tap do |html|  @report.information.each do |information|    information.history.each |history|        history.map do |history|        change[:items].map do |item|          [item[:field], item[:value], item[:value_formatted]].join("")        end      end      end   end  

I can easily have the information displayed in the console, but cannot through the pdf service. I think the reason why is because of how things are mapped out, and i'm not sure if i'm able to grab that data and have it displayed via the html that i've been using in the rest of the page.

My best guess has been what I have below, but I did not get anywhere with it.

html << "<div>#{[item[:field], item[:value], item[:value_formatted]].join("")}</div>"  

Could anybody take a look?

thanks in advance.

iframe or JS to embed Rails in 3rd party sites?

Posted: 18 Jul 2016 08:12 AM PDT

I want to create embedable widgets for a Rails app, that would allow users to interact with the app from external websites.

I was all set to try using iframes to achieve this. But then I found a couple of forum responses that seemed to suggested iframes are not the best way to achieve this, and instead to use JS to embed HTML elements. This surprised me - I thought iframes would be a clear winner simply because of the isolation of CSS and scripts.

So, what is the best way to embed (limited) app functionality in a third party website. This interaction will be limited to login and a single simple form. Is iframes of JS embed the best way to go? And as a side question, are there security issues to be aware of with either approach?

I am trying to collect links containing a key word, but it is saying that it cannot find any, when i know there are

Posted: 18 Jul 2016 07:09 AM PDT

I am trying to collect links containing a key word, but it is saying that it cannot find any, when i know there are

Here is what i am running:

def scrapelinks    mechanize = Mechanize.new    page = mechanize.get('https://www.reddit.com/r/soccer/')    link = page.link_with(text: 'transfer')    page = link.click    puts page.uri    page  end  

And here is the error code:

undefined method 'click' for nil:NilClass  

This is happening because there are no links with the word 'transfer', when i know there are. What is causing this to happen? Is it because the link has no spaces?

rails generate command doesn't work after installed metasploit framework

Posted: 18 Jul 2016 07:06 AM PDT

I experienced this problem: after I installed metasploit framework, I can not run some rails command, such as 'rails generate'. When I run rails generate controller ControllerName action1 action2, I get this error:

FATAL: Listen error: unable to monitor directories for changes.  

I dont't know what's wrong with my rails, how can I use rails command normally like I do before install metasploit? Sorry for my bad english, thanks in advance :)

Conflict between the ckeditor and non ckeditor dirty form checkers

Posted: 18 Jul 2016 06:59 AM PDT

I need to do a dirty form checker both on the regular rails fields and also on ckeditor ckedit textareas. It seems that I can get one or the other to work, but not both.

Both javascript_tag s are in edit.html.erb

<%= content_for(:body_attributes) do %> data-no-turbolink <% end %>    < %= javascript_tag do %>      var do_on_load = function() {      $('form').areYouSure( {'silent':false} );      $('form').areYouSure();      };      $(document).ready(do_on_load);      $(window).bind('page:change', do_on_load);  < % end %>  

The javascript for the ckeditor, also in edit.html.erb is

<%=  javascript_tag do %>        var checkChangesEnabled = true;      window.onbeforeunload = function (e) {      var e = e || window.event;      var isDirty = false;      for (var i in CKEDITOR.instances) {      if(CKEDITOR.instances[i].checkDirty())      {      isDirty = true;      }      }        if (isDirty == true && checkChangesEnabled) {      e.returnValue = 'Your document has UNSAVED CHANGES  If you continue those changes will be LOST.';      disableCheck();      }      }        function disableCheck() {      checkChangesEnabled = false;      setTimeout("enableCheck()", "100");      }        function enableCheck() {      checkChangesEnabled = true;      }    <% end %>  

If I remove one, the other works and vice versa. However, if I try to use both, only the second JS for the ckeditor textarea works. Apparently I am running into a conflict when I try to check both the regular rails fields and the ckeditor fields.

========================== jqery.are_you_sure.js ========================

/*!   * jQuery Plugin: Are-You-Sure (Dirty Form Detection)   * https://github.com/codedance/jquery.AreYouSure/   *   * Copyright (c) 2012-2014, Chris Dance and PaperCut Software http://www.papercut.com/   * Dual licensed under the MIT or GPL Version 2 licenses.   * http://jquery.org/license   *   * Author:  chris.dance@papercut.com   * Version: 1.9.0   * Date:    13th August 2014   */  (function($) {      $.fn.areYouSure = function(options) {        var settings = $.extend(        {          'message' : 'You have unsaved changes!',          'dirtyClass' : 'dirty',          'change' : null,          'silent' : false,          'addRemoveFieldsMarksDirty' : false,          'fieldEvents' : 'change keyup propertychange input',          'fieldSelector': ":input:not(input[type=submit]):not(input[type=button])"        }, options);        var getValue = function($field) {        if ($field.hasClass('ays-ignore')            || $field.hasClass('aysIgnore')            || $field.attr('data-ays-ignore')            || $field.attr('name') === undefined) {          return null;        }          if ($field.is(':disabled')) {          return 'ays-disabled';        }          var val;        var type = $field.attr('type');        if ($field.is('select')) {          type = 'select';        }          switch (type) {          case 'checkbox':          case 'radio':            val = $field.is(':checked');            break;          case 'select':            val = '';            $field.find('option').each(function(o) {              var $option = $(this);              if ($option.is(':selected')) {                val += $option.val();              }            });            break;          default:            val = $field.val();        }          return val;      };        var storeOrigValue = function($field) {        $field.data('ays-orig', getValue($field));      };        var checkForm = function(evt) {          var isFieldDirty = function($field) {          var origValue = $field.data('ays-orig');          if (undefined === origValue) {            return false;          }          return (getValue($field) != origValue);        };          var $form = ($(this).is('form'))                       ? $(this)                      : $(this).parents('form');          // Test on the target first as it's the most likely to be dirty        if (isFieldDirty($(evt.target))) {          setDirtyStatus($form, true);          return;        }          $fields = $form.find(settings.fieldSelector);          if (settings.addRemoveFieldsMarksDirty) {                        // Check if field count has changed          var origCount = $form.data("ays-orig-field-count");          if (origCount != $fields.length) {            setDirtyStatus($form, true);            return;          }        }          // Brute force - check each field        var isDirty = false;        $fields.each(function() {          $field = $(this);          if (isFieldDirty($field)) {            isDirty = true;            return false; // break          }        });          setDirtyStatus($form, isDirty);      };        var initForm = function($form) {        var fields = $form.find(settings.fieldSelector);        $(fields).each(function() { storeOrigValue($(this)); });        $(fields).unbind(settings.fieldEvents, checkForm);        $(fields).bind(settings.fieldEvents, checkForm);        $form.data("ays-orig-field-count", $(fields).length);        setDirtyStatus($form, false);      };        var setDirtyStatus = function($form, isDirty) {        var changed = isDirty != $form.hasClass(settings.dirtyClass);        $form.toggleClass(settings.dirtyClass, isDirty);          // Fire change event if required        if (changed) {          if (settings.change) settings.change.call($form, $form);            if (isDirty) $form.trigger('dirty.areYouSure', [$form]);          if (!isDirty) $form.trigger('clean.areYouSure', [$form]);          $form.trigger('change.areYouSure', [$form]);        }      };        var rescan = function() {        var $form = $(this);        var fields = $form.find(settings.fieldSelector);        $(fields).each(function() {          var $field = $(this);          if (!$field.data('ays-orig')) {            storeOrigValue($field);            $field.bind(settings.fieldEvents, checkForm);          }        });        // Check for changes while we're here        $form.trigger('checkform.areYouSure');      };        var reinitialize = function() {        initForm($(this));      }        if (!settings.silent && !window.aysUnloadSet) {        window.aysUnloadSet = true;        $(window).bind('beforeunload', function() {          $dirtyForms = $("form").filter('.' + settings.dirtyClass);          if ($dirtyForms.length == 0) {            return;          }          // Prevent multiple prompts - seen on Chrome and IE          if (navigator.userAgent.toLowerCase().match(/msie|chrome/)) {            if (window.aysHasPrompted) {              return;            }            window.aysHasPrompted = true;            window.setTimeout(function() {window.aysHasPrompted = false;}, 900);          }          return settings.message;        });      }        return this.each(function(elem) {        if (!$(this).is('form')) {          return;        }        var $form = $(this);          $form.submit(function() {          $form.removeClass(settings.dirtyClass);        });        $form.bind('reset', function() { setDirtyStatus($form, false); });        // Add a custom events        $form.bind('rescan.areYouSure', rescan);        $form.bind('reinitialize.areYouSure', reinitialize);        $form.bind('checkform.areYouSure', checkForm);        initForm($form);      });    };  })(jQuery);  

============================ end jquery.are_you_sure.js ========================

Rails Paper Trails delete existing versions with the condition

Posted: 18 Jul 2016 06:58 AM PDT

I want to delete the old entries of an entity in the 'versions' table with the following conditions

  1. First, It should be sorted by the recently modified

  2. I would like to remove all records which have more than 10 entries for an entity (i.e. a single row)

Is there a query which I can use to delete this.

My current proposal to remove such versions is as follows:-

entities.each do |entity|     versions = entity.versions.order('created_at DESC')     if versions.count > 10       #deleting all remaining versions except the 10 entries     end  end  

disable has_secure_password in API rails app

Posted: 18 Jul 2016 06:57 AM PDT

I've got a Rails app which is a webapp and at the same time also an API app for mobile users. In short, they share the same codebase.

The webapp has authentication using has_secure_password. As the API part is for mobile users, I don't want it to have passwords at all.

Everytime I submit a form for signup on the mobile app, it returns an error Password can't be blank. even though it doesn't have a password field ( as I don't want passwords for mobile users).

How do I get rid of password checking in the API namespace?

Would this mean that aside from the app/models/user.rb for the webapp I would also create a separate user.rb in the app/models/api/user.rb namespace and not have has_secure_password in it?

send_file link not working Ruby on Rails

Posted: 18 Jul 2016 07:39 AM PDT

I'm trying to download file instead of opening them in browser - file types can be different- so far i have below settings - it does nothing

In views

 <td><%= link_to "Download", download_file_path(resume) %></td>  

In controller

  def download_file(file_path)      mime = MIME::Types.type_for(file).first.content_type      send_file(file_path, :type => mime, :disposition => "attachment")    end  

In routes

 get 'profiles/download_file'          => 'profiles#download_file' , as: :download_file  

These settings works for nothing , page just refreshes - FYI: I'm using carrierwave for attachments

UPDATES: Logs Shown in console

Started GET "/profiles/download_file.2" for 127.0.0.1 at 2016-07-18 19:25:23 +0500 Processing by ProfilesController#show as Parameters: {"id"=>"download_file"}

Ruby on Rails 5 - seeds.rb

Posted: 18 Jul 2016 07:56 AM PDT

Is there any specification I need to stick to on seeds.rb file? When I rake db:seed, I get the response "rake aborted"

I am using rails 5.0.0

Any help will be greatly appreciated. Thanks.

enter code here    bdme551@bdme551:~/bdme/bin$ rails db:seed --trace  Looks like your app's ./bin/rails is a stub that was generated by Bundler.    In Rails 5, your app's bin/ directory contains executables that are versioned  like any other source code, rather than stubs that are generated on demand.    Here's how to upgrade:      bundle config --delete bin    # Turn off Bundler's stub generator    rails app:update:bin          # Use the new Rails 5 executables    git add bin                   # Add bin/ to source control    You may need to remove bin/ from your .gitignore as well.    When you install a gem whose executable you want to use in your app,  generate it and add it to source control:      bundle binstubs some-gem-name    git add bin/new-executable    ** Invoke db:seed (first_time)  ** Execute db:seed  ** Invoke db:abort_if_pending_migrations (first_time)  ** Invoke environment (first_time)  ** Execute environment  ** Invoke db:load_config (first_time)  ** Execute db:load_config  ** Execute db:abort_if_pending_migrations  ============= WARNING FROM mysql2 =============  The options :user, :pass, :hostname, :dbname, :db, and :sock will be deprecated at some point in the future.  Instead, please use :username, :password, :host, :port, :database, :socket, :flags for the options.  ============= END WARNING FROM mysql2 =========  rails aborted!  NoMethodError: undefined method `to_i' for {:name=>"FirstName"}:Hash  Did you mean?  to_s                 to_a                 to_h  /home/bdme551/bdme/app/models/user.rb:8:in `initialize'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/inheritance.rb:65:in `new'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/inheritance.rb:65:in `new'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/persistence.rb:33:in `create'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/persistence.rb:31:in `block in create'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/persistence.rb:31:in `collect'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/persistence.rb:31:in `create'  /home/bdme551/bdme/db/seeds.rb:11:in `<top (required)>'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0/lib/active_support/dependencies.rb:287:in `load'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0/lib/active_support/dependencies.rb:287:in `block in load'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0/lib/active_support/dependencies.rb:259:in `load_dependency'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0/lib/active_support/dependencies.rb:287:in `load'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/engine.rb:549:in `load_seed'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/tasks/database_tasks.rb:268:in `load_seed'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/railties/databases.rake:196:in `block (2 levels) in <top (required)>'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/task.rb:248:in `block in execute'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/task.rb:243:in `each'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/task.rb:243:in `execute'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/task.rb:187:in `block in invoke_with_call_chain'  /home/bdme551/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/task.rb:180:in `invoke_with_call_chain'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/task.rb:173:in `invoke'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/application.rb:152:in `invoke_task'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/application.rb:108:in `block (2 levels) in top_level'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/application.rb:108:in `each'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/application.rb:108:in `block in top_level'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/application.rb:117:in `run_with_threads'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/application.rb:102:in `top_level'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/commands/rake_proxy.rb:13:in `block in run_rake_task'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/application.rb:178:in `standard_exception_handling'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/commands/rake_proxy.rb:10:in `run_rake_task'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/commands/commands_tasks.rb:51:in `run_command!'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/commands.rb:18:in `<top (required)>'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/app_loader.rb:46:in `require'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/app_loader.rb:46:in `block in exec_app'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/app_loader.rb:35:in `loop'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/app_loader.rb:35:in `exec_app'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/cli.rb:5:in `<top (required)>'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/exe/rails:9:in `require'  /home/bdme551/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/exe/rails:9:in `<top (required)>'  /home/bdme551/.rvm/gems/ruby-2.3.1/bin/rails:23:in `load'  /home/bdme551/.rvm/gems/ruby-2.3.1/bin/rails:23:in `<main>'  /home/bdme551/.rvm/gems/ruby-2.3.1/bin/ruby_executable_hooks:15:in `eval'  /home/bdme551/.rvm/gems/ruby-2.3.1/bin/ruby_executable_hooks:15:in `<main>'  Tasks: TOP => db:seed  bdme551@bdme551:~/bdme/bin$   

user.rb

   class User < ActiveRecord::Base    has_many :roles    ROLES = {0 => :guest, 1 => :user, 2 => :moderator, 3 => :admin}        attr_reader :role      def initialize(role_id = 0)      @role = ROLES.has_key?(role_id.to_i) ? ROLES[role_id.to_i] : ROLES[0]    end      def role?(role_name)      role == role_name    end  end  

seeds.rb

    # This file should contain all the record creation needed to seed the database with its default values.  # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).  #  # Examples:  #  #   cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])  #   Mayor.create(name: 'Emanuel', city: cities.first)    # DELETED - REBASED VERSION!!!    users = User.create([       { name: 'FirstName' }, { name: 'LastName' }, { user_id: 'userid'} ])        # {name: "Lecture 8", user_id: 1, link: "http://flatiron-school.s3.amazonaws.com/ruby-003/reviews/playister-associations-with-artists.mp4", description: "Playlister App - Associations with Artists", lecture_date: "10/11/2013"},     supplies = Supplies.create([      { description: 'description' }, { medline_id: 'medline_id' }, { vendor: 'vendor' }, { HCPCS: 'HCPCS' } ])  #   {body: "Installing the **Guard gem** to automatically run rspec tests after each Rails file save action.", video_timestamp: 3783.467413, video_id: 5, created_at: "2013-12-04 20:55:41", updated_at: "2013-12-04 22:08:00", user_id: 3}  # ])    # notes_steph = Note.create([  #   {body: "We use groupings for gems to specify which environments gems are active in.  Here, the rspec, capybara, and selenium gems are grouped in both the test and development environments.", video_timestamp: 2408.407864, video_id: 5, created_at: "2013-12-04 20:54:11", updated_at: "2013-12-04 20:54:11", user_id: 2},  #   {body: "Drawing the routes for the ```Post``` controller via a resource, which generates the 7 standard routes: index, new, create, edit, update, show, and destroy. ", video_timestamp: 4257.238568, video_id: 5, created_at: "2013-12-04 20:58:44", updated_at: "2013-12-04 20:58:44", user_id: 2},  #   {body: "Side-by-side comparison of routes with the `Post` controller.  Shows how a certain route corresponds to a specific action within a controller.", video_timestamp: 5100.092628, video_id: 5, created_at: "2013-12-04 21:00:50", updated_at: "2013-12-04 21:00:50", user_id: 2},  #   { body: "![DHH](http://static.guim.co.uk/sys-images/Technology/Pix/pictures/2007/12/12/heinemeier.article.jpg 'DHH')", video_timestamp: 5661.311041, video_id: 5, created_at: "2013-12-04 21:05:03", updated_at: "2013-12-04 21:05:03", user_id: 2},  #   { body: "\n\n- - Review routes\n- - Relationship between MVC\n- - Basics of CRUD app\n- - Best Practices", video_timestamp: 6357.539163, video_id: 5, created_at: "2013-12-04 21:07:32", updated_at: "2013-12-04 22:00:02", user_id: 2},  #   {body: "**Generating a Rails App** - what's the importance of `-T` ?", video_timestamp: 125, video_id: 5, created_at: "2013-12-04 20:41:41", updated_at: "2013-12-04 22:07:09", user_id: 2},  #   {body: "**Reviewing the Gemfile** - what does the 'turbolink' gem do?", video_timestamp: 590.109342, video_id: 5, created_at: "2013-12-04 20:44:01", updated_at: "2013-12-04 22:07:16", user_id: 2},  #   {body: "**Gem Version Notation:** `~> 4.0.0` means to use any minor version greater than 4.0.0 and less than 4.1.0.  `>= 1.3.0` means to use the most recent version greater than 1.3.0.", video_timestamp: 612.732023, video_id: 5, created_at: "2013-12-04 20:50:02", updated_at: "2013-12-04 22:07:24", user_id: 2},  #   {body: "Differences between the **test, development, and production databases**. Development is a database that's used during the feature development process, whereas production is a database that's used for production purposes.", video_timestamp: 1157.556356, video_id: 5, created_at: "2013-12-04 20:52:15", updated_at: "2013-12-04 22:07:44", user_id: 2},  #   {body: "Installing the **Guard gem** to automatically run rspec tests after each Rails file save action.", video_timestamp: 3783.467413, video_id: 5, created_at: "2013-12-04 20:55:41", updated_at: "2013-12-04 22:08:00", user_id: 2}  # ])    # notes_saron = Note.create([  #   {body: "We use groupings for gems to specify which environments gems are active in.  Here, the rspec, capybara, and selenium gems are grouped in both the test and development environments.", video_timestamp: 2408.407864, video_id: 5, created_at: "2013-12-04 20:54:11", updated_at: "2013-12-04 20:54:11", user_id: 4},  #   {body: "Drawing the routes for the ```Post``` controller via a resource, which generates the 7 standard routes: index, new, create, edit, update, show, and destroy. ", video_timestamp: 4257.238568, video_id: 5, created_at: "2013-12-04 20:58:44", updated_at: "2013-12-04 20:58:44", user_id: 4},  #   {body: "Side-by-side comparison of routes with the `Post` controller.  Shows how a certain route corresponds to a specific action within a controller.", video_timestamp: 5100.092628, video_id: 5, created_at: "2013-12-04 21:00:50", updated_at: "2013-12-04 21:00:50", user_id: 4},  #   { body: "![DHH](http://static.guim.co.uk/sys-images/Technology/Pix/pictures/2007/12/12/heinemeier.article.jpg 'DHH')", video_timestamp: 5661.311041, video_id: 5, created_at: "2013-12-04 21:05:03", updated_at: "2013-12-04 21:05:03", user_id: 4},  #   { body: "\n\n- - Review routes\n- - Relationship between MVC\n- - Basics of CRUD app\n- - Best Practices", video_timestamp: 6357.539163, video_id: 5, created_at: "2013-12-04 21:07:32", updated_at: "2013-12-04 22:00:02", user_id: 4},  #   {body: "**Generating a Rails App** - what's the importance of `-T` ?", video_timestamp: 125, video_id: 5, created_at: "2013-12-04 20:41:41", updated_at: "2013-12-04 22:07:09", user_id: 4},  #   {body: "**Reviewing the Gemfile** - what does the 'turbolink' gem do?", video_timestamp: 590.109342, video_id: 5, created_at: "2013-12-04 20:44:01", updated_at: "2013-12-04 22:07:16", user_id: 4},  #   {body: "**Gem Version Notation:** `~> 4.0.0` means to use any minor version greater than 4.0.0 and less than 4.1.0.  `>= 1.3.0` means to use the most recent version greater than 1.3.0.", video_timestamp: 612.732023, video_id: 5, created_at: "2013-12-04 20:50:02", updated_at: "2013-12-04 22:07:24", user_id: 4},  #   {body: "Differences between the **test, development, and production databases**. Development is a database that's used during the feature development process, whereas production is a database that's used for production purposes.", video_timestamp: 1157.556356, video_id: 5, created_at: "2013-12-04 20:52:15", updated_at: "2013-12-04 22:07:44", user_id: 4},  #   {body: "Installing the **Guard gem** to automatically run rspec tests after each Rails file save action.", video_timestamp: 3783.467413, video_id: 5, created_at: "2013-12-04 20:55:41", updated_at: "2013-12-04 22:08:00", user_id: 4}  # ])  

How to have ruby 2.3.1 as a default version

Posted: 18 Jul 2016 06:49 AM PDT

I am an absolute beginner of ruby on rails and even web development.

I use Mac OS(El captain 10.11.3)

I would like to ask you how I can use ruby 2.3.1 anytime I would like to develop my project. It seems like that I can use ruby 2.3.1 for good. (Below is the version I would like to use)

ruby -v  ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]  

This may sound odd, but whenever I get my terminal closed, the version of ruby in my laptop goes back to

ruby -v  ruby 2.0.0p645 (2015-04-13 revision 50299) [universal.x86_64-darwin15]  

So when I try to develop my project, I always do this

source ~/.bash_profile  

The above command allows me to use ruby 2.3.1.

What I want to do is not to put the command "source ~/.bash_profile" when I open my ruby project.

Has anyone encountered any similar problem before? If you have, please leave your comments below. English is not my first language, so if this post does not make sense or you need more information, please let me know as well

Any advice would be appreciated! Thanks in advance!

Rails: Not able to download rmagick gem on windows machine

Posted: 18 Jul 2016 06:35 AM PDT

I am trying to install rmagick gem but not able to install it. i have already download imagemagick software(ImageMagick-7.0.2-4-Q16-x64-dll.exe) available for windows 7 64 bit machine from here http://www.imagemagick.org/script/binary-releases.php#windows.

i am trying to install rmagick gem by using below command

gem install rmagick --version=2.15.4 --platform=ruby -- --with-opt-lib=C:/ImageMagick/lib --with-opt-include=C:/ImageMagick/include   

But i am getting below error

Temporarily enhancing PATH to include DevKit...  Building native extensions with: '--with-opt-lib=C:/ImageMagick/lib --with-opt-i  nclude=C:/ImageMagick/include'  This could take a while...  ERROR:  Error installing rmagick:          ERROR: Failed to build gem native extension.        C:/Ruby200-x64/bin/ruby.exe extconf.rb --with-opt-lib=C:/ImageMagick/lib --w  ith-opt-include=C:/ImageMagick/include  *** extconf.rb failed ***  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may  need configuration options.    Provided configuration options:          --with-opt-dir          --without-opt-dir          --with-opt-include=${opt-dir}/include          --with-opt-lib=${opt-dir}/lib          --with-make-prog          --without-make-prog          --srcdir=.          --curdir          --ruby=C:/Ruby200-x64/bin/ruby  extconf.rb:110:in ``': No such file or directory - identify -version (Errno::ENO  ENT)          from extconf.rb:110:in `configure_compile_options'          from extconf.rb:16:in `initialize'          from extconf.rb:517:in `new'          from extconf.rb:517:in `<main>'      Gem files will remain installed in C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/rmagi  ck-2.15.4 for inspection.  Results logged to C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/rmagick-2.15.4/ext/RMa  gick/gem_make.out  

I don't know why rmagick gem is not installing. i have search on the internet about this issue and have followed all the solutions but non of them work for it.

Please help

Carrierwave - crop image before upload?

Posted: 18 Jul 2016 06:31 AM PDT

I am trying to implement image cropping into my rails app. I watched this railscast https://www.youtube.com/watch?v=ltoPZEzmtJA but it looks like the file is uploaded then it brings you to another page to crop. Is it possible to crop the image before uploading it, or at least do it all at the same time?

Better PNG compression

Posted: 18 Jul 2016 06:27 AM PDT

I'd like to set the final image to png (for either jpg or png uploaded logos) and also better compress it using the PNG: flags as described at http://www.imagemagick.org/script/command-line-options.php#quality. How do I use those flags with paperclip? Will it result in good enough compression or is it better to use plugins such as paperclip-optimizer and paperclip-compression?

Rails Console Freezes on manual delete/destroy action

Posted: 18 Jul 2016 06:26 AM PDT

This has happened to me on numerous occasions and I hope I can find an answer here.

Sometimes when working with the Rails console and performing an #update or #destroy action on an object, my console will simply freeze after posting "BEGIN" in the log. I currently have one open, a simple destroy, that has been sat there for ten minutes.

i.e.:

my_object.find(permitted_params[:thing][:id]).destroy  

CTRL+C on my mac does not kill it and simply renders:

^C^C^C^C^C^C^C^C^C^C  

Then when I finally kill the tab and restart the server I get:

A server is already running. Check /path/to/app/tmp/pids/server.pid.  

Then when I clear server.pid and try to restart the server I get:

/Users/nickschwaderer/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/socket.rb:206:in `bind': Address already in use - bind(2) for 127.0.0.1:3000 (Errno::EADDRINUSE)  

At that point I run lsof -wni tcp:3000, then kill -9 #whatever_my_pid_was, to finally set everything straight to re run the server.

What in the sam blue heck is happening here?

How to preserve state between tasks

Posted: 18 Jul 2016 06:47 AM PDT

I am trying to write an app which:

  1. Gets some data from external service API (let it be just a number) every N minutes,
  2. Makes actions if received data differ from the previous saved state.

To achieve that, I have a controller:

class MyController < ApplicationController        # to be called every N minutes      def check          if @saved_state.nil?              @saved_state = get_from_API              return          end            @new_state = get_from_API            if @saved_state != @new_state              process              @saved_state = @new_state          end      end        def process          # some data processing here      end        def get_from_API          # getting data from external API here      end  end  
  1. How can I save state between check calls? What is the right way to achieve the described goal?
  2. Is it OK to use a controller for that, or is there some more appropriate solution, another approach?
  3. I plan to use rake task via cron for calling check every N minutes: something like MyController.new.check. Is it OK, or is there another way to regularly call some app method on the server?

Rails 4 - Update just some values in model on before_update

Posted: 18 Jul 2016 06:38 AM PDT

I have an edit form in which I don't allow the user to update some values by disabling some fields. Also, I want to disallow the updates at model level using the before_update callback.

I can do it by resetting the fields that I don't want to update to their previous values.

Is there a 'whitelist' way of doing this? I mean, what if I want to only allow the update of the 'name' and 'price' fields and let the others fields unmodified?

I've come to this:

def custom_update    name = self.name    price = self.price    self.restore_attributes    self.name = name    self.price = price  end  

Can I do it better?

Redirect a url with only some get params in Rails 4

Posted: 18 Jul 2016 06:16 AM PDT

I am developing an application that should still respond to some old urls from a previous web application. I would like to build some redirects to an action only when a param(get param) is present. for instance

get '/students/:id?school_id=(:id)', to: redirect { |params, req|       # path of the a known action here  }  

How will recognize urls like this:

/students/:id?school_id=25957,

but NOT urls like this:

/students/:id?address=345

How do I split a key in hashes in Rails?

Posted: 18 Jul 2016 08:30 AM PDT

I want to break the key as I want to compare their values. Below 63 represents id, rest is time.

[63, Thu, 14 Jul 2016 09:01:14 UTC +00:00]=>3.0  

Versioning an unversioned grape API

Posted: 18 Jul 2016 07:11 AM PDT

I'm working on a Rails app that uses grape for its API. Currently, there's a single version of the API that is mounted in the root folder (not v1, as I would like), and I need to start creating v2. The current version is mounted as follows:

/app/api/api.rb:

module API    class Base < Grape::API      logger Rails.logger        mount API::Things         => '/things'  end  

and then I have /app/api/api/things.rb with something like:

module API    class Things < Grape::API      get '/' do      end    end  end  

Basically, the API is mounted in /api/things with a hardcoded path. I need to:

  • Make this API the v1 without changing its path.
  • Create a v2 path.

So, I changed api.rb to be:

module API    class Base < Grape::API      mount API::V1::Base      mount API::V2::Base    end  end  

and created api/api/v1/base.rb as follows:

module API    module V1      class Base < Grape::API        version 'v1', using: :accept_version_header          mount API::Things         => '/things'      end    end  end  

and then the same for v2:

module API    module V2      class Base < Grape::API        version 'v2`          mount API::V2::Things         => '/things'      end    end  end  

My problem is that /things does not inherit the /v2 path component as I would expect. Therefore, since v1 is mounted in /things, v2 fails to mount there.

If I write v2 to use resources instead of paths as v1 is, it works, but I'd like to keep the mounts as is, to make v2 consistent with v1.

MongoDB - Metadata

Posted: 18 Jul 2016 06:56 AM PDT

I integrated my rails application with MongoDB using mongo gem. I would like to know how I can store metadata about each collection.

  def initialize(db_params)      db = Mongo::Connection.new(connection_uri[:host], connection_uri[:port])      @collection = db.db(db_params[:key]).collection(db_params[:collection])    end  

More precisely I want to add some metadata during creating new collection and then be able to read that before other database actions like find.

Serving assets for mailer from S3

Posted: 18 Jul 2016 06:42 AM PDT

I have an email template which requires image, I decided to serve it through S3 bucket.

In template:

<%= image_tag 'logo.png' %>  

application.rb:

config.action_mailer.asset_host = "https://s3.mybucket.com"  

But after template is rendered I get url like this:

"https://s3.mybucket.com/logo-1ee47e184c8a345a78d06117ad1b04f560256a5002ad5c5b798c41b1a.png"

Am I missing some steps here?

No comments:

Post a Comment