Sunday, May 15, 2016

Many to many with polymorphic association doesn't work in both directions | Fixed issues

Many to many with polymorphic association doesn't work in both directions | Fixed issues


Many to many with polymorphic association doesn't work in both directions

Posted: 15 May 2016 06:53 AM PDT

I am implementig the system that enable user to follow the "followable"( in my case these may be an event, place or other user).

My idea:

Follow model holds the user_id, followable type and followale_id(join table)

class Follow < ActiveRecord::Base    belongs_to :user    belongs_to :followable, polymorphic: true  end  

Event

class Event < ActiveRecord::Base        has_many :follows, as: :followable    has_many :users, through: :follows  end  

Place

class Place < ActiveRecord::Base    has_many :follows, as: :followable    has_many :users, through: :follows      end  

User

class User < ActiveRecord::Base    has_many :follows    has_many :events, through: :follows, source: :followable, source_type: "Event"    has_many :locals, through: :follows, source: :followable, source_type: "Local"    has_many :users, through: :follows, source: :followable, source_type: "User"  end  

The problem is that the realtion works only in one direction, i can do:

user.follows.create(followable:event1) #follow event1  user.follows.create(followable:place1) #follow place1  user.follows.create(followable:user1)  #follow user1  user.follows # displays all following relations user has established  

But, i cannot do:

event1.follows #return follow objects(some user - event1 pairs)  event1.users #return all of the users that follow this event  user1.users  #return all of the users that user1 follows, the most confusing part..  

All of the aboves return nil.

How should i establish the relations to make it work in both directions?
Also, i'd like to hear some remarks on how to improve this idea, beacouse it's the first time i'm playin around with more complex realtions. Thank you in advance.

Every RSpec test run requires rake db:test:prepare or equivalent using Rails 4.2.5

Posted: 15 May 2016 06:38 AM PDT

Using Ruby 2.0.0, Rails 4.2.5, RSpec 3.4.4, Shoulda-matcher 3.1.1, Database_cleaner 1.4.0, PostgreSQL 9.4.5.

For every rspec (or rake spec) I have to prepare the test database. If I don't, I receive the "Migrations are pending." message. Everything I read tells me this is not right given Rails 4.1+. I've taken every corrective action that I can find to no avail.

Preparing the test database means I either use "rake db:test:prepare", which is deprecated, or a series of "rake db:drop/create/migrate RAILS_ENV=test". Either works. A simple migrate after a test does not work as it tries to recreate all the tables though they exist. None of these problems exist in development or on Heroku production as all migrations are processed and work fine.

Rails_helper.rb contains the command "ActiveRecord::Migration.maintain_test_schema!" which should control this problem. In actual fact, that command is the one that identifies that a migration is required and throws the "Migrations are pending." message. I tried including the command "ActiveRecord::Migrator.migrate(File.join(Rails.root, 'db/migrate'))" to check and force a migration if required, but that is the same as running a new migrate and causes the problem I mentioned about recreating existing tables.

I did use "rails generate rspec:install" to rebuild .rspec, spec_helper.rb and rails_helper.rb and then update the new files to try to solve the problem. I also migrated all of my configurations over to rails_helper.rb. spec_helper.rb is all comments.

The failure is as follows:

rake spec   Running rails_helper.rb  D:/BitNami/rubystack-2.0.0-38/ruby/lib/ruby/gems/2.0.0/gems/activerecord-4.2.5/lib/active_record/migration.rb:392:in `check_pending!':  (ActiveRecord::PendingMigrationError)  Migrations are pending. To resolve this issue, run:          bin/rake db:migrate RAILS_ENV=test  

.rspec

--color  --format documentation  --require rails_helper  

rails_helper.rb

# This file is copied to spec/ when you run 'rails generate rspec:install'  puts "Running rails_helper.rb"  ENV['RAILS_ENV'] ||= 'test'  require File.expand_path('../../config/environment', __FILE__)    abort("The Rails environment is not running in test mode!") unless Rails.env.test?    require 'rspec/rails'  # Add additional requires below this line. Rails is not loaded until this point!  require 'shoulda/matchers'    Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f; puts "File #{f}" }    ActiveRecord::Migration.maintain_test_schema!  #ActiveRecord::Migrator.migrate(File.join(Rails.root, 'db/migrate'))    RSpec.configure do |config|    config.extend ControllerMacros, type: :controller    config.include JsonSpec::Helpers    config.render_views  # Intended to ensure that views are processed      config.expect_with :rspec do |expectations|      expectations.include_chain_clauses_in_custom_matcher_descriptions = true    end      # ## Mock Framework    config.mock_with :mocha    # config.mock_with :flexmock    # config.mock_with :rr      # If you're not using ActiveRecord, or you'd prefer not to run each of your    # examples within a transaction, remove the following line or assign false    # instead of true.    config.use_transactional_fixtures = true      # If true, the base class of anonymous controllers will be inferred    # automatically. This will be the default behavior in future versions of    # rspec-rails.    config.infer_base_class_for_anonymous_controllers = false      # Run specs in random order to surface order dependencies. If you find an    # order dependency and want to debug it, you can fix the order by providing    # the seed, which is printed after each run.    #     --seed 1234    config.order = "random"      # rspec-rails 3 will no longer automatically infer an example group's spec type    # from the file location. You can explicitly opt-in to this feature using this    # snippet:    config.infer_spec_type_from_file_location!      # Filter lines from Rails gems in backtraces.    config.filter_rails_from_backtrace!    # arbitrary gems may also be filtered via:    # config.filter_gems_from_backtrace("gem name")      # Sorcery RSpec configuration    # config.include Sorcery::TestHelpers::Rails::Controller, type: [:controller]    # config.include Sorcery::TestHelpers::Rails::Integration, type: [:feature]    config.include Sorcery::TestHelpers::Rails      # FactoryGirl RSpec configuration    config.include FactoryGirl::Syntax::Methods    end  

Gemfile

source 'https://rubygems.org'  ruby '2.0.0'  gem 'rails', '4.2.5'  gem 'sprockets', '3.4.0'   gem 'sprockets-rails', '2.3.3'  gem 'sass', '3.4.19'  gem 'sass-rails', '5.0.4'  gem 'uglifier', '2.7.1'  gem 'coffee-rails', '4.1.0'  gem 'turbolinks', '2.5.3'  gem 'jquery-turbolinks', '2.1.0'    gem 'jbuilder', '2.2.13'  gem 'will_paginate', '~> 3.0.7'  gem 'bootstrap-sass', '3.3.5.1'  gem 'figaro', '1.1.1'   gem 'pg', '0.18.1'  gem 'simple_form', '3.1.0.rc2'  gem 'sorcery', '0.9.1'  gem 'rolify', '4.0.0'  gem 'acts_as_tenant', '0.3.9'  gem 'jquery-datatables-rails', '3.3.0'  gem 'jquery-rails', '4.0.4'    gem 'jquery-ui-rails', '5.0.5'  gem 'lodash-rails', '3.7.0'  gem 'logging', '2.0.0'  gem 'smarter_csv', '1.0.19'  gem 'addressable', '2.3.8'  gem 'delayed_job', '4.0.6'  gem 'delayed_job_active_record', '4.0.3'  gem 'better_delayed_job_web', '1.3.12'  gem 'roo', '2.0.1'  gem 'roo-xls', '1.0.0'  gem 'font-awesome-sass', '4.3.2.1'  gem 'autoprefixer-rails', '5.2.0'  gem 'twilio-ruby', '4.7.0'  gem 'exception_notification', '4.1.1'   gem 'exception_notification-rake', '0.2.1'   gem 'tzinfo-data'      gem 'responders', '2.1.0'  gem 'rubyzip', '1.1.7'        gem 'htmlentities', '4.3.3'   gem 'axlsx', '2.1.0.pre'  gem 'axlsx_rails', '0.3.0'  gem 'acts_as_xlsx', '1.0.6'  gem 'spreadsheet', '1.0.3'  gem 'redis', '3.2.1'  gem 'aws-sdk', '2.1.35'  gem 'aws-sdk-core', '2.1.35'  gem 'aws-sdk-resources', '2.1.35'  gem 'phony', '2.15.10'  gem 'phony_rails', '0.12.11'  gem 'ranger', '1.1.0'  gem 'execjs', '2.6.0'  gem 'paloma', '4.2.1'  gem 'rabl-rails', '0.4.2'  gem 'gon', '6.0.1'  group :production, :staging do    platforms :ruby do # Linux      gem 'unicorn', '4.9.0'    end    platforms :mswin do # Windows      gem 'passenger', '5.0.8'    end    gem 'rails_12factor', '0.0.3'  # For Heroku    end  group :development do    gem 'brakeman', require: false    gem 'web-console', '2.1.3'    gem 'bullet', '4.14.7'    gem 'better_errors', '2.1.1'    gem 'binding_of_caller', '0.7.2'    gem 'quiet_assets', '1.1.0'    gem 'rails_layout', '1.0.26'    gem 'meta_request', '0.4.0'    gem 'coffee-rails-source-maps', '1.4.0'  end  group :development, :test do    gem 'thin', '1.6.3'    gem 'letter_opener', '1.3.0'    gem 'factory_girl_rails', '4.5.0'    gem 'rspec-core', '3.4.4'    gem 'rspec-rails','3.4.2'    gem 'rspec-collection_matchers', "1.1.2"  end  group :test do    gem 'database_cleaner', '1.4.0'    gem 'email_spec', '1.6.0'    gem 'shoulda-matchers', '3.1.1', require: false    gem 'shoulda-callback-matchers', '1.1.3'    gem 'mocha', '1.1.0'    gem 'json_spec', '1.1.4'    gem 'pry', '0.10.1'    gem 'capybara', '2.4.4'    gem "faker", "~> 1.4.3"    gem "forgery", "~> 0.6.0"    gem "launchy", "~> 2.4.3"    gem "selenium-webdriver", "~> 2.53.0"  end  

database_cleaner.rb

RSpec.configure do |config|      config.before(:suite) do      DatabaseCleaner.clean_with(:truncation)    end      config.before(:each) do      DatabaseCleaner.strategy = :transaction    end      config.before(:each, :js => true) do      DatabaseCleaner.strategy = :truncation    end      config.before(:each) do      DatabaseCleaner.start    end      config.after(:each) do      DatabaseCleaner.clean    end    end  

I couldn't read images and jsons of Cesiumjs on Ruby onRails

Posted: 15 May 2016 06:32 AM PDT

Environments ・Ruby on Rails 4.2.1 ・Cesium 1.7(bower-rails) ・develop mode

Because of these errors, I couldn't read images and jsons of Cesiumjs. I also found an error of CSS (but it's not cause 404)

localhost:3000/cesiumjs/Cesium/Assets/IAU2006_XYS/IAU2006_XYS_15.json 404 localhost:3000/cesiumjs/Cesium/Assets/Textures/SkyBox/tycho2t3_80_px.jpg 404 . . . about:blank:1 Blocked script execution in 'about:blank' because the document's frame is sandboxed and the 'allow-scripts' permission is not set.

I confirmed the path of these images and jsons. But they exist in vendor/assets/cesiumjs/Cesium/Assets/

localhost:3000/bower_components/cesiumjs/Cesium/Widgets/widgets.css localhost:3000/cesiumjs/Cesium/Widgets/InfoBox/InfoBoxDescription.css

↑These errors are about CSS. I found these errors but widget.css is applied. And I tried to access by rails console, I can get 200. I can't find their causes. Please teach me....

Code is here

application.html.erb

<!DOCTYPE html>   <html>    <head>     <title>CodeRails</title>     <style>      #cesiumContainer {       position: absolute;       top: 0;       left: 0;       height: 100%;       width: 100%;       margin: 0;       overflow: hidden;       padding: 0;       font-family: sans-serif;     }       html {      height: 100%;     }       body {      padding: 0;      margin: 0;      overflow: hidden;      height: 100%;     }    </style>    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>    <%= csrf_meta_tags %>  </head>  <body>   <div id="cesiumContainer"></div>   <script>    window.CESIUM_BASE_URL = '/cesiumjs/Cesium/Cesium';    var viewer = new Cesium.Viewer('cesiumContainer',{      imageryProvider : new Cesium.ArcGisMapServerImageryProvider({          url : 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',          enablePickFeatures : false      }),      navigationHelpButton : false,      navigationInstructionsInitiallyVisible : false,      geocoder:false,      timeline: false,      animation: false,      sceneModePicker:false,      baseLayerPicker:false,      scene3DOnly : true  });  viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);     </script>   <%= yield %>  </body>  

application.js

//= require jquery  //= require jquery_ujs  //= require turbolinks  //= require_tree .  //= require cesiumjs  

application.css

*= require_tree .   *= require cesiumjs/cesium/widgets/widgets   *= require_self   */  

application.rb

require File.expand_path('../boot', __FILE__)    require 'rails/all'    # Require the gems listed in Gemfile, including any gems  # you've limited to :test, :development, or :production.  Bundler.require(*Rails.groups)    module CodeRails    class Application < Rails::Application       config.active_record.raise_in_transactional_callbacks = true       config.assets.paths << Rails.root.join('vendor', 'assets', 'bower_components')       root.join('vendor', 'assets', 'bower_components').to_s.tap do |bower_path|        config.sass.load_paths << bower_path        config.assets.paths << bower_path      end    end  end  

pass number_field value to rails controller with ajax

Posted: 15 May 2016 06:42 AM PDT

I want to pass value from

number_field_tag

to my rails controller on click of this event

:onclick => "getVal()"

my javascript and ajax is like this

function getVal(){       var quant = document.getElementById("quantity").value;      console.log(quant);      $.ajax({      type: 'POST',       url: '/carts/add_to_cart',      dataType: 'json',      data: { quant }     });  return false;  }  

and my route is this on which I want to send data
post '/cart/:product_id' => 'carts#add_to_cart', as: 'add_to_cart'
my route is fine I have checked.. but stuck in ajax.. I think my ajax code has some problem. My browser console is showing this error,
http://localhost:3000/carts/add_to_cart 404 (Not Found)
Please check if there is any problem.

Not receiving money in Stripe test transactions (Rails)

Posted: 15 May 2016 06:25 AM PDT

So I created subscriptions in my Rails app with test API keys from Stripe. The charges I'm creating with dummy cards are going through successfully on my side, but when I'm in Stripe dashboard, the test balance remains the same, as well customer details are not added. I'm not sure what I did wrong.. Do you know why I can't and how can I add those test customer data to Stripe? In the logs, I'm getting 200 OK response, but I'm worried that something isn't going to function in live mode since test balance isn't being updated.

class SubscribersController < ApplicationController       before_filter :authenticate_user!        def new      end        def update          token = params[:stripeToken]          customer = Stripe::Customer.create(            card: token,            plan: 1020,            email: current_user.email            )          current_user.subscribed = true          current_user.stripeid = customer.id          current_user.save            redirect_to profiles_user_path      end      end  

and _form.html.erb

<%= form_tag profiles_user_path, method: :get do %>      <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"            data-key="<%= Rails.configuration.stripe[:publishable_key] %>"            data-description="A month's subscription"            data-amount="8999"></script><span> $89 per month </span>  <% end %>     

Rails asset pipeline - custom js files

Posted: 15 May 2016 05:48 AM PDT

I have couple of js files in application.js file. Such as;

//= require jquery  //= require jquery_ujs  //= require dropzone  //= require jquery.cookie  //= require toastr    //VENDOR JS BEGINS  //= require pace/pace.min    //= require modernizr.custom  //= require jquery-ui/jquery-ui.min  //= require boostrapv3/js/bootstrap.min  //= require jquery/jquery-easy  //= require jquery-unveil/jquery.unveil.min  //= require jquery-bez/jquery.bez.min  //= require jquery-ios-list/jquery.ioslist.min  //= require jquery-actual/jquery.actual.min  //= require jquery-scrollbar/jquery.scrollbar.min  //= require bootstrap-select2/select2.min  //= require switchery/js/switchery.min  //= require imagesloaded/imagesloaded.pkgd.min  //= require jquery-isotope/isotope.pkgd.min  //= require classie/classie  //= require codrops-stepsform/js/stepsForm  //= require bootstrap-datepicker/js/bootstrap-datepicker  //= require bootstrap-datepicker/js/locales/bootstrap-datepicker.tr.js  //= require bootstrap-datepicker/js/locales/bootstrap-datepicker.en.js  //= require summernote/js/summernote.min  //= require moment/moment-with-locales.min  //= require bootstrap-daterangepicker/daterangepicker  //= require bootstrap-timepicker/bootstrap-timepicker.min  //= require codrops-dialogFx/dialogFx  //= require ion-slider/ion.rangeSlider.min  //= require owl-carousel/owl.carousel.min  

I have also couple of js codes in the html.erb pages. But I want to take all page specific js codes into 1 file. This file should be called after page loads. Because some of them uses ruby code such as init lat lng of google maps. Also, couple of js files such as;

    //= require codrops-dialogFx/dialogFx     //= require ion-slider/ion.rangeSlider.min   

works after page loads. So, they do not work as I put them to head tag as;

<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>      

So If I, design application.js as;

//= require jquery  //= require jquery_ujs  //= require dropzone  //= require jquery.cookie  //= require toastr  

Then call <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> in head tag then call all the other js files in the body tag like

<%= javascript_include_tag 'pace/pace.min', 'data-turbolinks-track' => true %>  <%= javascript_include_tag 'modernizr.custom', 'data-turbolinks-track' => true %>  <%= javascript_include_tag 'jquery-ui/jquery-ui.min', 'data-turbolinks-track' => true %>  <%= javascript_include_tag 'boostrapv3/js/bootstrap.min', 'data-turbolinks-track' => true %>  ....  

Does rails precompiles these files also?. I have these js files in vendor file.

If selection = ?..then, how to decrease the a value of an integer attribute?

Posted: 15 May 2016 06:42 AM PDT

i am working with a reservation system and i am having problem with the constraints.. i have a list of cottages with a number of cottages vacant.. a working sytem i swhen the customer reserve a cottage the number of vacant cottage need to decrease.. please help me i have here some codes i started... and an image to help you understand my explanation..

what i want to accomplish here is:

Before a reservation: Cottage Availability: 5

if i fill up information & select "small cottage" and create reservation the availability value will -1.

After a reservation: Cottage availability: 4

form.html.erb

<%= form_for(@reservation) do |f| %>      <%= f.label :reservation_date %><br>    <%= f.date_select :reservation_date %>      <%= f.label :customer_name %><br>    <%= f.text_field :customer_name %>      <%= f.label :address%><br>    <%= f.text_field :address %>      <%= f.label :contact_no %><br>    <%= f.text_field :contact_no %>      <%= f.label :cottage_class %><br>    <%= f.select :cottage_id, options_for_select( Cottage.all.map { |g| [g.name, g.id]}) %>      <%= f.submit %>  <% end %>   

schema.rb

ActiveRecord::Schema.define(version: 20160514141006) do      create_table "cottages", force: :cascade do |t|      t.string   "name"      t.string   "rates"      t.integer  "no_of_vacant_cottage"      t.datetime "created_at",   null: false      t.datetime "updated_at",   null: false    end      create_table "reservations", force: :cascade do |t|      t.date     "reservation_date"      t.string   "customer_name"      t.string   "address"      t.string   "contact_no"      t.datetime "created_at",       null: false      t.datetime "updated_at",       null: false      t.integer  "cottage_id"    end      add_index "reservations", ["cottage_id"], name: "index_reservations_on_cottage_id"    end  

reservation.rb

class Reservation < ActiveRecord::Base    validates :customer_name, :presence => true    validates :address, :presence => true    validates :contact_no, :presence => true      belongs_to :cottage  end  

cottage.rb

class Cottage < ActiveRecord::Base    has_many :reservations  end  

Form and list of cottages existing on the database

Could not find rake-11.1.2 in rails docker container

Posted: 15 May 2016 05:29 AM PDT

I'm running two docker containers. One with rails and one with Postgres db. Here is my docker-compose file:

# Docs: https://docs.docker.com/compose/compose-file/  version: '2'  services:    db:      image: postgres      environment:         - POSTGRES_PASSWORD=xxx      rails:      build: .      command: rails s -p 3000 -b '0.0.0.0'      volumes:        - .:/app      ports:        - "3000:3000"      links:        - db      depends_on:        - db  

Here the Dockerfile for the rails app:

FROM ruby:2.3    RUN apt-get update   RUN apt-get install -y build-essential nodejs     RUN mkdir -p /app  WORKDIR /app    COPY Gemfile Gemfile.lock ./   RUN gem install bundler && bundle install --jobs 20 --retry 5    COPY . ./    EXPOSE 3000    ENTRYPOINT ["bundle", "exec"]    CMD ["rails", "server", "-b", "0.0.0.0"]  

When I run docker-compose up everything works fine and I can connect to the server via the ip address from docker-machine.

When I try to connect to the container with the following command:

docker-compose run rails console  

I get this error:

Could not find rake-11.1.2 in any of the sources  Run `bundle install` to install missing gems.  

bundle install inside the container has no effect and the mentioned gem is definitely installed. In other stack-overflow questions were mentioned that I should run bin/spring stop. So I ran:

docker-compose run bin/spring stop  

And it returns:

Spring is not running  

I'm still comparibly new to ruby/rails and docker. I hope someone can help me here! Thanks in advance

PS: Comments on the Dockerfiles are appreciated!

How to do rake db:migrate:reset using capistrano

Posted: 15 May 2016 04:41 AM PDT

I am using capistrano for deploying my rails app to digitalocean server. I have came into a situation where I need to run rake db:migrate:reset and rake db:reset.. I have done it in development and it worked. But can I do it using capistrano in production?

Here is my deploy.rb

# config valid only for current version of Capistrano  lock '3.5.0'    set :application, 'appname'  set :repo_url, 'myrepo.git'    # Default branch is :master  # ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp    # Default deploy_to directory is /var/www/my_app_name  set :deploy_to, '/home/deploy/myapp'    set :linked_files, %w{config/application.yml}  set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system}    # Default value for :scm is :git  # set :scm, :git    # Default value for :format is :airbrussh.  # set :format, :airbrussh    # You can configure the Airbrussh format using :format_options.  # These are the defaults.  # set :format_options, command_output: true, log_file: 'log/capistrano.log', color: :auto, truncate: :auto    # Default value for :pty is false  # set :pty, true    # Default value for :linked_files is []  # set :linked_files, fetch(:linked_files, []).push('config/database.yml', 'config/secrets.yml')    # Default value for linked_dirs is []  # set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'public/system')    # Default value for default_env is {}  # set :default_env, { path: "/opt/ruby/bin:$PATH" }    # Default value for keep_releases is 5  # set :keep_releases, 5    namespace :deploy do      after :restart, :clear_cache do      on roles(:web), in: :groups, limit: 3, wait: 10 do        # Here we can do anything such as:        # within release_path do        #   execute :rake, 'cache:clear'        # end      end    end    end  

Nested resource failing to update

Posted: 15 May 2016 04:30 AM PDT

I'm trying to do what I think should be simple: do a simple edit on a single text string field with the default update action. But it just doesn't seem to work, despite many attempts and alterations.

There are no errors and the flash message responds successfully, but information isn't saved to the database at all:

routes.rb

resources :interviews do    resources :invitations do      put :accept    end  end  

views/invitations/edit.html.haml

= simple_form_for [@interview, @invitation] do |f|    = f.error_notification    = f.input :testing    = f.submit 'Edit Invitstion', :class => 'button small'  

controllers/invitations_controller.rb

def update    @invitation = Invitation.find(params[:id])    @interview = Interview.find(params[:interview_id])      @invitation.update_attributes(invitation_params)      if @invitation.update_attributes(invitation_params)      redirect_to edit_interview_invitation_path(@interview, @invitation), notice:  "Your profile has been successfully updated."    else      render action: "edit"    end  end    private    def invitation_params    params.permit(:user_id, :interview_id, :invitation_id, :session_time, :workflow_state, :testing)  end  

And here's the log:

Started PATCH "/interviews/3/invitations/7" for ::1 at 2016-05-15 19:01:52 +0800  Processing by InvitationsController#update as HTML    Parameters: {"utf8"=>"✓", "authenticity_token"=>"o0U5t0yPN0aE2er+DWK0uxqRGyp4ywfdSrEfvwiSQ3UUaOnr3Fd0raFs1IUqVzizKoqxRU0DDpmvysntB9fdhQ==", "invitation"=>{"interview_id"=>"3", "workflow_state"=>"invited", "session_time"=>"", "testing"=>"testtesttest"}, "commit"=>"Edit Invitstion", "interview_id"=>"3", "id"=>"7"}    User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 7]]    Invitation Load (0.2ms)  SELECT  "invitations".* FROM "invitations" WHERE "invitations"."id" = $1 LIMIT 1  [["id", 7]]    Role Load (0.2ms)  SELECT  "roles".* FROM "roles" WHERE "roles"."id" = $1 LIMIT 1  [["id", 3]]    Interview Load (0.2ms)  SELECT  "interviews".* FROM "interviews" WHERE "interviews"."id" = $1  ORDER BY created_at DESC LIMIT 1  [["id", 3]]    CACHE (0.0ms)  SELECT  "invitations".* FROM "invitations" WHERE "invitations"."id" = $1 LIMIT 1  [["id", "7"]]    CACHE (0.0ms)  SELECT  "interviews".* FROM "interviews" WHERE "interviews"."id" = $1  ORDER BY created_at DESC LIMIT 1  [["id", "3"]]  Unpermitted parameters: utf8, _method, authenticity_token, invitation, commit, id     (0.1ms)  BEGIN    Invitation Exists (0.4ms)  SELECT  1 AS one FROM "invitations" WHERE ("invitations"."user_id" = 3 AND "invitations"."id" != 7 AND "invitations"."interview_id" = 3) LIMIT 1     (0.1ms)  COMMIT  Redirected to http://localhost:3000/interviews/3/invitations/7/edit  Completed 302 Found in 12ms (ActiveRecord: 1.6ms)      Started GET "/interviews/3/invitations/7/edit" for ::1 at 2016-05-15 19:01:52 +0800  Processing by InvitationsController#edit as HTML    Parameters: {"interview_id"=>"3", "id"=>"7"}    User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 7]]    Invitation Load (0.3ms)  SELECT  "invitations".* FROM "invitations" WHERE "invitations"."id" = $1 LIMIT 1  [["id", 7]]    Role Load (0.2ms)  SELECT  "roles".* FROM "roles" WHERE "roles"."id" = $1 LIMIT 1  [["id", 3]]    Interview Load (0.2ms)  SELECT  "interviews".* FROM "interviews" WHERE "interviews"."id" = $1  ORDER BY created_at DESC LIMIT 1  [["id", 3]]    Rendered invitations/edit.html.haml within layouts/application (6.1ms)  Completed 200 OK in 48ms (Views: 39.1ms | ActiveRecord: 1.6ms)  

Overriding a concern of a gem - Rails

Posted: 15 May 2016 06:47 AM PDT

I am trying to modify a gem (Devise token auth to be precise) to suit my needs. For that I want to override certain functions inside the concern SetUserByToken.

The problem is how do I override that?

I don't want to change the gem files. Is there an easy/standard way of doing that?

how to resize image properly without cutting the image using RMagic in rails

Posted: 15 May 2016 04:00 AM PDT

i have a product section in my apps where products are listed with there photos in a frame i use rmagic gem to upload image and AWS S3 to store them, my problem is when ever i upload an image which is bigger in height or width the image get cropped:

My product index page

<head>      <link href="/assets/bootstrap.min.css" rel="stylesheet">      <link href="/assets/font-awesome.min.css" rel="stylesheet">      <link href="/assets/products.css" rel="stylesheet">  </head>  <a class="btn btn-info btn-sm" href="#success" data-toggle="modal"><h4><i class="fa fa-shopping-cart"></i></h4></a>  <body>  <div class="container-fluid">    <div class="text-center">      <h1>Store Of The Champions</h1>    </div>  <p id="notice"><%= notice %></p>  <% @products.each do |product| %>  <div class="wrap ">         <h1><%= product.name %></h1>         <div class="imagesize" >         <h6><%= image_tag product.image.url(:medium)%></h6>       </div>         <p>Description: <%= product.description %></p>          <p>Size: <%= product.size %></p>          <p>Avaliable Colours: <%= product.colour %></p>           <div class="text-center">         <h6>₹ <%= product.price %></h6>        </div>      </div>    <% end %>  </div>      <!-- Modal -->      <div class="modal fade" id="success" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">          <div class="modal-dialog">              <div class="modal-content">                  <div class="modal-header modal-header-success">                      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>                      <h1><i class="fa fa-shopping-cart"></i> How to order?</h1>                  </div>                  <div class="modal-body">                    To order any product just call us @ +919038215052                  </div>                  <div class="modal-footer">                      <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>                  </div>              </div><!-- /.modal-content -->          </div><!-- /.modal-dialog -->      </div><!-- /.modal -->    </body>  

my product modal

class Product < ActiveRecord::Base      belongs_to :user      has_attached_file :image, styles: { medium: "1280x720#" }, :default_url => "missing.jpg"    validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/  end  

my product css

body {      font-size: 11px;      font-family: 'Open Sans', sans-serif;      color: #4A4A4A ;      text-align: center;  }  .wrap {      background: #fff;      margin: 20px auto;      display: block;      width: 300px;      height: 380px;      padding:20px;      border-radius: 2px 2px 2px 2px;       -webkit-box-shadow: 0 1px 4px       rgba(0, 0, 0, 0.3), 0 0 40px       rgba(0, 0, 0, 0.1) inset;      -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;      box-shadow: 0 1px 4px       rgba(0, 0, 0, 0.3), 0 0 40px       rgba(0, 0, 0, 0.1) inset;      float: left;      margin-right: 29px;  }    .wrap img {      width: 100%;      margin-top: 15px;  }    p{       margin-top: 15px;      text-align: justify;  }    h1{      font-size: 20px;      font-weight: bold;      margin-top: 5px;       text-shadow: 1px 1px 3px rgba(0,0,0,0.3);  }    a{      text-decoration: none;      color: #4A4A4A !important;  }    a:hover{      text-decoration: underline;      color: #6B6B6B !important ;  }    .imagesize {    max-width: 1280px;    max-height: 1280px;  }  

Map one controller action on another action rails

Posted: 15 May 2016 05:00 AM PDT

I have a controller named carts_controller and in my routes I am using restful routes i.e., resources :carts.

I know resources create default actions like create, index etc., but if I don't want to user create and create a method add_to_cart and in routes I have defined its route as

post '/add_cart/:product_id/' => 'carts#add_to_cart', as: 'add_to_cart'   

Does this route considered RESTFUL?

I don't want to user all the default RESTFUL routes created by resources. I want some custom actions in place of these. My code is working but I am confused as my concepts are not clear. Another thing is if I know that I need product_id in my routes, should I make them nested inside products resources or it will work if I define custom ad I defined above?

Any help would be appreciated!

Rails simple form undefined method `model_name' for nil:NilClass

Posted: 15 May 2016 04:28 AM PDT

I want to create a simple form to make new reviews for a recipe that has been posted in a cookbook. I render the review form on the recipe show page, but it keeps giving me the same error:

undefined method `model_name' for nil:NilClass

Here is my code:

Simple form for:

<%= simple_form_for(@review, url: recipe_reviews_path(@recipe)) do |f| %>      <%= f.error_notification %>      <%= f.input :content %>      <%= f.input :rating %>      <%= f.button :submit, class: "btn btn-success" %>  <% end %>  

Reviews controller:

class ReviewsController < ApplicationController    def new      @recipe = recipe.find(params[:recipe_id])      @review = Review.new(review_params)    end      def create      @recipe = recipe.find(params[:recipe_id])      @review = Review.new(review_params)      @review.recipe = @recipe      if @review.save        redirect_to recipe_path(@recipe)      else        render 'recipe/show'      end    end      private      def review_params      params.require(:review).permit(:content, :rating)    end  end  

Recipes controller:

class RecipesController < ApplicationController    skip_before_action :authenticate_user!    def index      @recipes = Recipe.all    end      def show      @recipe = Recipe.find(params[:id])      @user = User.find(@recipe.user_id)      @full_name = @recipe.user.first_name + " " + @recipe.user.last_name    end  end  

Recipe show page:

<div class="review">    <%= render 'review/new' %>      <% @recipe.reviews.each do |review| %>        <%= review.content %>        <%= review.rating %>    <% end %>  </div>  

Routes:

 resources :recipes, only: [:index, :show] do      resources :reviews, only: [:create]    end  

Models:

class Recipe < ActiveRecord::Base    belongs_to :user    has_many :ingredients, dependent: :destroy    has_many :reviews, dependent: :destroy      validates :name, :summary, :course, :kitchen, :photo, :description, presence: true    validates :summary, length: { maximum: 30 }    mount_uploader :photo, PhotoUploader      accepts_nested_attributes_for :ingredients, reject_if: :all_blank, allow_destroy: true  end  

model review:

class Review < ActiveRecord::Base    belongs_to :recipe      validates :content, length: { minimum: 20 }    validates :rating, presence: true    validates_numericality_of :rating, :greater_than_or_equal_to => 0, :less_than_or_equal_to => 5    validates :content, presence: true  end  

Can anyone see the problem? Thank you in advance!

Paperclip error after test completed

Posted: 15 May 2016 03:46 AM PDT

I have a problem with testing paperclip with dropzone. Basically the test works 100% ok, but after the test being executed it calls routing error, because the app didn't find the image, that was currently processed in test. I tested the correctness of image link created, it's there.
Basically I have this test:

let!(:announcement3) do        create(:announcement, announcement_images: [create(:announcement_image), create(:announcement_image)])  end    it 'can set second image as primary' do      login_as user, scope: :user      visit edit_area_announcement_path(announcement3.slug)      click_link I18n.t('simple_form.buttons.announcements.next')      all('[data-primary="not_set"]')[1].click      click_link I18n.t('simple_form.buttons.announcements.finish')      expect(Announcement.last.main_image_index).to eq(Announcement.last.announcement_images.last.id)    end  

And after this test completes, I receive this error: Failure/Error: Unable to find matching line from backtrace

 ActionController::RoutingError:     No route matches [GET] "/home/vyivrain/Documents/Job/pets/public/system/announcement_images/images/000/000/001/original/synchronised-5th-generation-alliance-magni.jpg"   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/rack/logger.rb:38:in `call_app'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/rack/logger.rb:20:in `block in call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/tagged_logging.rb:68:in `block in tagged'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/tagged_logging.rb:26:in `tagged'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/tagged_logging.rb:68:in `tagged'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/rack/logger.rb:20:in `call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/request_id.rb:21:in `call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/methodoverride.rb:22:in `call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/runtime.rb:18:in `call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/lock.rb:17:in `call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/static.rb:120:in `call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/sendfile.rb:113:in `call'   # ./app/middleware/rack/robots_middleware.rb:12:in `call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:518:in `call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/application.rb:165:in `call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/urlmap.rb:66:in `block in call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/urlmap.rb:50:in `each'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/urlmap.rb:50:in `call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/capybara-2.6.2/lib/capybara/server.rb:19:in `call'   # /home/vyivrain/.rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/handler/webrick.rb:88:in `service'  

I just have no idea why it triggers this url and tries to find this image. From stack error, there's only robots_middleware.rb, but that's only refering to robots.txt, it's not possible, that the error is there.

Thanks for answering

Ruby on Rails: Why does <Object>.all succeed, yet <Object.find(:all) fails?

Posted: 15 May 2016 03:05 AM PDT

Following are 2 outputs from rails console:

1. Success

irb(main):038:0> Category.all    Category Load (0.0ms)  SELECT "categories".* FROM "categories"  => #<ActiveRecord::Relation [#<Category id: 1, name: "tutorials", created_at: "2016-05-14 18:44:38", updated_at: "2016-05-14 18:44:38">, #<Category id: 2, name: "news", created_at: "2016-05-14 18:44:38", updated_at: "2016-05-14 18:44:38">, #<Category id: 3, name: "design", created_at: "2016-05-14 18:44:38", updated_at: "2016-05-14 18:44:38">]>  

2. Failure

irb(main):039:0> Category.find(:all)    Category Load (0.0ms)  SELECT  "categories".* FROM "categories" WHERE "categories"."id" = $1 LIMIT 1  [["id", nil]]  ActiveRecord::RecordNotFound: Couldn't find Category with 'id'=all          from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/relation/finder_methods.rb:324:in `raise_record_not_found_exception!'          from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/relation/finder_methods.rb:444:in `find_one'          from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/relation/finder_methods.rb:423:in `find_with_ids'          from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/relation/finder_methods.rb:71:in `find'          from h:in `find'          from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/core.rb:130:in `find'          from (irb):39          from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.3/lib/rails/commands/console.rb:110:in `start'          from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.3/lib/rails/commands/console.rb:9:in `start'          from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:68:in `console'          from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:39:in `run_command!'          from h:/rails/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.3/lib/rails/commands.rb:17:in `<top (required)>'          from bin/rails:4:in `require'          from bin/rails:4:in `<main>'  irb(main):040:0>  

Rails ParameterMissing error on create action

Posted: 15 May 2016 04:57 AM PDT

When I try to create a user, Rails returns a ParameterMissing error:

ActionController::ParameterMissing in UserController#create  param is missing or the value is empty: user  

My Controller

class UserController < ApplicationController    def create          @user = User.new(user_params)    render json: @user  end    private    def user_params      params.require(:user).permit(:fame, :lame, :mobile)    end  end  

My User Model

class User < ActiveRecord::Base    self.table_name = "user"  end  

What am I doing wrong?

Undefined method 'update_attributes' for nil:NilClass

Posted: 15 May 2016 04:47 AM PDT

i'm trying to update_attributes with this private method and due to the association, i thought i could call cart.update_attributes but for some reason, it is returning an undefined method. Someone please tell me what i'm doing wrong.

Thanks in advance!

class PaymentNotification < ActiveRecord::Base    belongs_to :cart    serialize :params    after_create :mark_cart_as_purchased       private      def mark_cart_as_purchased      if status == "Completed"        cart.update_attribute(:purchased_at, Time.now)      end    end  end  

I have installed railties ...but shows error Could not find proper version of railties (4.2.3) in any of the sources

Posted: 15 May 2016 01:46 AM PDT

using cloud9 IDE enter image description here

Loading jquery datepicker stylesheet

Posted: 15 May 2016 02:02 AM PDT

I am using the jquery datepicker. If I put in my application.css.scss file

@import 'jquery-ui/datepicker';  

the styles for the datepicker are not loaded.

But if I put

@import 'jquery-ui/datepicker.css';  

the styles are loaded, but when I precompile my assets there is no digest file for /assets/jquery-ui/datepicker.css and so it is not included in the application.css digest in production. This means the styling does not working in production.

What is the correct way to import this file? I am using the sassc and jquery-ui-rails gems.

link_to with anchor renders the post and then the anchor

Posted: 15 May 2016 05:01 AM PDT

When I use:

<%= link_to reply.pid, board_post_path(@board.slug, post, anchor: reply.pid) %>  

The browser first goes to /board.slug/post.pid and then it goes to /board.slug/post.pid#reply.pid needing back button to be pressed twice to return to the previous page.

How do I fix this, and why is it happening?

posts_controller.rb:

class PostsController < ApplicationController      def show      @board = Board.friendly.find(params[:board_id])      @boards = Board.all      @post = Post.includes(:board).where('boards.slug' => params[:board_id]).friendly.find(params[:id])    end      def create      @board = Board.friendly.find(params[:board_id])      @postf = Post.all      @post = @board.posts.create(post_params)      if @post.email.to_s == 'stay'        @post.update_attributes(:email => nil)        redirect_to action: "show", id: @post.id      elsif !@post.save        flash[:error] = @post.errors.full_messages        redirect_to :back      else        redirect_to :back      end    end      def destroy      @post = Post.friendly.find(params[:id])      @post.destroy      redirect_to :back    end      private      def post_params      params.require(:post).permit(:name, :email, :subject, :comment, :post_file, :post_file_original_name)    end    end  

I want to select an option from a generated list of model instances Rails

Posted: 15 May 2016 01:10 AM PDT

I want a select box with a generated option from a list of instances. Right now it looks like this but it isnt working.

<% current_admin.manager_approvals.each do |ma| %>     <% if ma.manager_approved == true %>        <option><%= select(:manager_approval, :manager_approval_id, [['<%= ma.manager_company %>&nbsp;|&nbsp;<%= ma.manager_phone] %>']]</option>      <% end %>    <% end %>  

It should make each instance an option to be chosen and pass that chosen option in the form. How can I correct this.

Authentication issue in Cap production deploy

Posted: 15 May 2016 12:56 AM PDT

Issue

(Backtrace restricted to imported tasks) cap aborted! Net::SSH::AuthenticationFailed: Authentication failed for user user@xxyy

Tasks: TOP => rvm:check (See full trace by running task with --trace)

I am following this tutorial to deploy rails app into my ec2 instance and am at the step where I key in cap production deploy

I have tried the solutions in this post, but am unable to resolve the situation.

Also, I have checked to ensure that my .pem file is located in the .ssh folder in my home directory. I am able to manually ssh into my ec2 instance.

How do I overcome the error above?

Notes:

1) Content of my production.rb

server 'xx.yyy.zz', user: 'abc', roles: %w{web app db}

2) net-ssh version is 3.1.1. I did not specify this gem in my Gemfile, but still found it from Gemfile.lock.

undefined method `get_me' for Class

Posted: 15 May 2016 12:52 AM PDT

I keep getting error undefined method get_me for #<Kele:0x007ff85a328610> when ever i try to call the get_me method for my API ruby gem .

class Kele     include HTTParty     base_uri 'https://www.bloc.io/api/v1'      def initialize(email, password)       response = self.class.post('/sessions',      body: { email: email, password: password } )        @auth_token = response['auth_token']      if @auth_token.nil?         puts "Sorry, invalid credentials."      end    end      def get_me      response = self.class.get('/users/me', headers: { "authorization" => @auth_token })      @current_user = JSON.parse(response.body)    end  end  

In console:

$ irb  >> require 'kele'  => true  >> kele_client = Kele.new("jane@gmail.com", "abc123")  >> kele_client.get_me  

Can't seem to figure out what is causing the error to raise.

rails use form input value before save

Posted: 15 May 2016 12:08 AM PDT

I have a form in rails with input values, and 1 of the values is a LOV (List of Values) and a second input field is also a LOV but depends on the input of the other field. The input value of the first field is not saved in between. So I need to use that field value before it is saved. So, the example: I choose a company from the list of values of all companies for the field supplier, the second field supplier_address will be a LOV with all the addresses of that company, so the LOV of the second field is dependent on the value chosen in the first field, company.

What I tried:

  def new      @purchase_requisition = PurchaseRequisition.new      @purchase_requisition.number = find_next_user_value("Purchase_Requisition")      #@purchase_requisition.supplier_address_id =  PurchaseRequisition.new.purchase_requisition_params[:supplier_id]      @purchase_requisition = PurchaseRequisition.new(purchase_requisition_params)        respond_to do |format|        @purchase_requisition.supplier_address_id = PurchaseRequisition.new.purchase_requisition_params[:supplier_id]      end    end  

but I still get the error:

param is missing or the value is empty: purchase_requisition

Can someone please help me? Thank you!!!

Get specific json data rails

Posted: 15 May 2016 12:40 AM PDT

I have this json data (actual data is a lot longer, that's why I need only 2)

 [    {      "id": 1,      "user_id": 1,      "event_id": 1,      "creator_id": 1,      "event_name": "Poker",      "cruise_ship_name": "Royal Cruise",    },    {      "id": 2,      "user_id": 1,      "event_id": 2,      "creator_id": 1,      "event_name": "Ballroom",      "cruise_ship_name": "Celebrity Infinity",    },    {      "id": 3,      "user_id": 1,      "event_id": 3,      "creator_id": 1,      "event_name": "Tennis",      "cruise_ship_name": "Mediterranean",    }  ]  

I want to combine all data and get only specific fields (event_name and cruise_ship_name)

So in my final json format

it will be:

[    {     "event_name": "Mexican Fiesta",     "cruise_ship_name": "Celebrity Infinity",    }  ]  

I have been looking at this example:

@object.to_json {:include => [ :assocation_a, :assocation_b ]}   

but not sure what :association_a and :association_b are.

activerecord-reputation system with has_many through assocations?

Posted: 14 May 2016 10:47 PM PDT

I would like to setup activerecord-reputation-system gem on my rails app and have the following issue. I have a projects model and a tasks model...however tasks are not necessarily associated with only a single project - they can have many projects. Because of this i created a TaskRelationship model to link tasks to projects.

User Model:

# for tracking tasks or projects a user created  has_many :own_projects, :class_name=>'Project'  has_many :own_tasks, :class_name=>'Task'  

Task Model:

belongs_to :owner, :foreign_key=>'user_id', :class_name=>'User'    has_many :taskrelationships, foreign_key: "projecttask_id",                                     class_name: "TaskRelationship",                                     dependent: :destroy  has_many :taskprojects, through: :taskrelationships, source: :taskproject  

Project Model:

belongs_to :owner, :foreign_key=>'user_id', :class_name=>'User'    has_many :reverse_taskrelationships, foreign_key: "taskproject_id",                                            class_name: "TaskRelationship",                                            dependent: :destroy  has_many :projecttasks, through: :reverse_taskrelationships, source: :projecttask  

TaskRelationship Model (associates a task with a project):

belongs_to :taskproject, class_name: "Project"  belongs_to :projecttask, class_name: "Task"  validates :taskproject_id, presence: true  validates :projecttask_id, presence: true    #i would like to add the votes on this task relationship, i.e,  #has_reputation :votes, source: :user, aggregated_by: :sum  #but I fear the gem may not work this way  

I would like the votes to be on the TaskRelationship so that it represents the most voted up tasks with regard to a single project only...From the front-end/UI, the users will be voting from a project profile page that lists out tasks that have been added to that specific project. I was hoping someone could provide some guidance on how to approach this or on whether it can even be accomplished this way...so i won't start off on the wrong foot. thx a lot.

Whenever Gem Daily email using actionmailer not sending

Posted: 14 May 2016 11:04 PM PDT

I can't seem to make the whenever gem work with my actionmailer. I am trying to run the application in development wherein an email would be sent to a specific individual at a specific time.

In my schedule.rb file I have the following:

every :day, :at => '12:48pm' do    runner "FoodPlan.food_email"  end  

In my controller called food_plans_controller.rb I have:

  def self.food_email      @food_plans = FoodPlan.where(food_plan_date: Date.today).order('meal ASC')        UserMailer.food_email(@food_plans).deliver_now    end  

In user_mailer.rb I have (take note I removed the email for privacy reasons) :

  def food_email (food)      @food_plans = food        mail(to: '---------@yahoo.com', subject: 'Food Orders for #{Date.today}')    end  

I have a folder in the views called user_mailer, inside it is a file called food_email.html.erb with the ff:

<!DOCTYPE html>  <html>      </head>    <body>      <h1>title</h1>      <p>        Good morning, -----!        <br><br>        Meal Plans for <%=Date.today%>:        <br><br>        <table class="table table-bordered table-striped">    <thead>      <tr>        <th>#</th>        <th>Meal Plan</th>        <th>Ordered by</th>        <th>Room Number</th>        <th>Received by</th>        <th>Signature</th>      </tr>    </thead>      <tbody>      <%countint=1%>      <% @food_plans.each do |food_plan| %>        <tr>          <td><%=countint%></td>          <td><%= food_plan.meal %></td>          <td><%=food_plan.applicant.first_name%>          <%=food_plan.applicant.last_name%></td>          <td><%=food_plan.applicant.room_number%></td>          <%countint+=1%>          <td></td>          <td></td>        </tr>      <% end %>        </tbody>  </table>        <br>        <br>        ---.        <br>        <br>        If you have any concerns, don't hesitate to call us at ------.          <br>        <br>        Thanks, <br>----      </p>    </body>  </html>   

In my development config I have (I removed the email and password):

  config.action_mailer.smtp_settings = {    address:              'smtp.gmail.com',    port:                 587,    domain:               'example.com',    user_name:            '-------',    password:             '-------',    authentication:       'plain',    enable_starttls_auto: true  }  

I have tried reading this guide but I cannot still get the gem to work with actionmailer. I have also read up on the documentation of the whenever gem but I still can't figure out what I'm doing wrong. :(

I'm not getting any errors, it's just that the email is not sending.

Using regex with highlight

Posted: 14 May 2016 10:01 PM PDT

I'm trying to highlight all lines in post.comment that start with $ using regex
<%= highlight(post.comment, /^\$.*$/) %>

However this returns the error no implicit conversion of Regexp into String

How can I format this to match every string starting with $?

$highlight test  test  $highlight test  

ActiveRecord Calculate the Sum of Columns and Group them

Posted: 14 May 2016 11:54 PM PDT

I have the following query

engagement_metrics = EngagementMetric.where(engagement_id: engagement_ids).order('metrics_date desc').limit(7).group_by { |p| p.metrics_date }  

which results in something like this

{      "2016-05-13": [          {              "id": 4,              "provider": "facebook",              "likes": -2,              "comments": 0,              "shares": 0,              "views": 0,              "reach": 0,              "reactions": {                  "sad_count": "0",                  "wow_count": "-1",                  "haha_count": "0",                  "like_count": "-1",                  "love_count": "0",                  "angry_count": "0"              }          },          {              "id": 5,              "provider": "facebook",              "likes": 2,              "comments": 2,              "shares": 2,              "views": 2,              "reach": 0,              "reactions": {                  "sad_count": "0",                  "wow_count": "0",                  "haha_count": "0",                  "like_count": "0",                  "love_count": "0",                  "angry_count": "0"              }          }      ],      "2016-05-12": [          {              "id": 3,              "provider": "facebook",              "likes": 1,              "comments": 3,              "shares": 0,              "views": 0,              "reach": 0,              "reactions": {                  "sad_count": "1",                  "wow_count": "0",                  "haha_count": "0",                  "like_count": "0",                  "love_count": "0",                  "angry_count": "0"              },              "engagement_id": 1,              "participation_id": 1,              "campaign_id": 1,              "influencer_authorization_id": 1,              "influencer_id": 1,              "social_account_id": 1,              "metrics_date": "2016-05-12",              "status": "processed",              "deleted_at": null,              "created_at": "2016-05-14T11:36:55.995Z",              "updated_at": "2016-05-14T11:36:55.995Z"          }      ],      "2016-05-11": [          {              "id": 2,              "provider": "facebook",              "likes": 0,              "comments": 16,              "shares": 0,              "views": 0,              "reach": 0,              "reactions": {                  "sad_count": "0",                  "wow_count": "0",                  "haha_count": "0",                  "like_count": "0",                  "love_count": "0",                  "angry_count": "0"              }          }      ],      "2016-05-10": [          {              "id": 1,              "provider": "facebook",              "likes": 3,              "comments": 4,              "shares": 0,              "views": 0,              "reach": 0,              "reactions": {                  "sad_count": "0",                  "wow_count": "1",                  "haha_count": "0",                  "like_count": "1",                  "love_count": "1",                  "angry_count": "0"              }          }      ]  }  

Which is the best way to iterate through to get data like below

[      {          "date": "24/03/16",          "metrics": {              "likes_count": "29",              "comments_count": "456",              "shares_count": "234",              "views_count": "65",              "clicks_count": "123"          }      },      {          "date": "25/03/16",          "metrics": {              "likes_count": "345",              "comments_count": "234",              "shares_count": "876",              "views_count": "345",              "clicks_count": "45"          }      },      {          "date": "26/03/16",          "metrics": {              "likes_count": "345",              "comments_count": "265",              "shares_count": "243",              "views_count": "165",              "clicks_count": "87"          }      },      {          "date": "27/03/16",          "metrics": {              "likes_count": "376",              "comments_count": "87",              "shares_count": "54",              "views_count": "754",              "clicks_count": "34"          }      },      {          "date": "28/03/16",          "metrics": {              "likes_count": "103",              "comments_count": "324",              "shares_count": "405",              "views_count": "87",              "clicks_count": "354"          }      },      {          "date": "29/03/16",          "metrics": {              "likes_count": "23",              "comments_count": "65",              "shares_count": "234",              "views_count": "87",              "clicks_count": "34"          }      },      {          "date": "30/03/16",          "metrics": {              "likes_count": "98",              "comments_count": "576",              "shares_count": "34",              "views_count": "365",              "clicks_count": "212"          }      }  ]  

No comments:

Post a Comment