Saturday, July 23, 2016

(Unable to autoload constant Cflag, expected /app/app/models/cflag.rb to define it) | Fixed issues

(Unable to autoload constant Cflag, expected /app/app/models/cflag.rb to define it) | Fixed issues


(Unable to autoload constant Cflag, expected /app/app/models/cflag.rb to define it)

Posted: 23 Jul 2016 07:50 AM PDT

I have a very basic Photo and Comments model that works and then I have a built a Cflags model that is used to flag comments. I am getting the following error from Heroku log when I visit the photos/show.html.erb view.

LoadError (Unable to autoload constant Cflag, expected /app/app/models/cflag.rb to define it)    photos/show.html.erb  .  .  <% @photo.comments.each do |comment| %>    <%= form_for([comment, Cflags.new]) do |f| %>      <%= f.hidden_field :user_id, value: current_user.id %>      <%= f.submit "Report Inappropiate" %>    <% end %>  <% end %>     PhotosController  def show    @photo = Photo.approved.find(params[:id])  end    CommentsController  def create     @photo = Photo.find(params[:photo_id])     @comment = @photo.comments.build(comment_params)     @comment.save     respond_to do |format|       format.html { redirect_to :back }       format.js      end   end       class CFlag < ActiveRecord::Base    belongs_to :comment, counter_cache: true    belongs_to :user, counter_cache: true    validates :user_id, presence: true     validates :comment_id, presence: true    validates :user_id, uniqueness: {       scope: [:comment_id],      message: 'You can only flag a comment once. Thank you for your feedback.'    }    default_scope -> { order(created_at: :desc) }  end    class CflagsController < ApplicationController  before_action :logged_in_user    def create    @comment = Comment.find(params[:comment_id])    @cflag = @comment.cflags.build(cflag_params)      if @cflag.save        if @comment.cflags_count > 1          @comment.update_attribute(:approved, false)            flash[:success] = "Flag created! Comment ##{@comment.id} has been removed for review. Thank you for your feedback"          redirect_to :back        else              flash[:success] = "Flag created! Thank you for your feedback"          redirect_to :back        end      else        redirect_to :back, notice: @cflag.errors.full_messages        end        end          private       def cflag_params        params.require(:cflag).permit(:user_id, :comment_id).merge(user_id: current_user.id)      end  end    resources :photos do    resources :comments do      resources :cflags    end  end    create_table "cflags", force: :cascade do |t|    t.integer  "comment_id"    t.integer  "user_id"    t.datetime "created_at", null: false    t.datetime "updated_at", null: false  end    add_index "cflags", ["comment_id"], name: "index_cflags_on_comment_id"  add_index "cflags", ["user_id"], name: "index_cflags_on_user_id"  

If I change the form to:

<% @photo.comments.each do |comment| %>    <%= form_for([comment, comment.cflags.build]) do |f| %>      <%= f.hidden_field :user_id, value: current_user.id %>      <%= f.submit "Report Inappropiate" %>    <% end %>  <% end %>       I get the same error:    LoadError (Unable to autoload constant Cflag, expected /app/app/models/cflag.rb to define it):  

backbone, marionette, NoItemViewError: An `itemView` must be specified

Posted: 23 Jul 2016 07:48 AM PDT

I defined a drop-down field populated with [city] collection within my [crew] edit app in Marionette. Its works fine, but since I want to re-use the code in many other apps/views, I re-defined it as a share component under backbone/components and called it "popuplist".

The issue is: I'm getting the "NoItemViewError" when I use my component "popuplist". All seems to be defined according to the previous use case, and I can't get it to work. This is a Marionette error and indeed after inspecting 'this' in the browser console, 'itemView' is not defined. But the thing is, it is actually defined within my popuplist/view. Somehow, after passing my drop-down field from the 'embedded' implementation to the backbone/components implementation, itemView is lost.

Code from the caller (Crew Edit App):

@MyApp.module "CrewApp.Edit", (Edit, App, Backbone, Marionette, $, _) ->    class Edit.Controller extends App.Controllers.Base        initialize: (options) ->          { crew, id } = options          crew or= App.request "crew:entity", id            @listenTo crew, "updated", ->              App.vent.trigger "crew:updated", crew            App.execute "when:fetched", crew , =>              @layout = @getLayoutView crew                @listenTo @layout, "show", =>                  @titleRegion crew                  @formRegion crew                  @cityRegion crew                @show @layout        titleRegion: (crew) ->          titleView = @getTitleView crew          @layout.titleRegion.show titleView        cityRegion: (crew) ->          cityView = App.request "popuplist:wrapper"          @layout.cityRegion.show cityView        formRegion: (crew) ->          editView = @getEditView crew            @listenTo editView, "form:cancel", ->              App.vent.trigger "crew:cancelled", crew            formView = App.request "form:wrapper", editView            @layout.formRegion.show formView        getTitleView: (crew) ->          new Edit.Title              model: crew        getLayoutView: (crew) ->          new Edit.Layout              model: crew        getEditView: (crew ) ->          new Edit.Crew              model: crew  

Code from [crew] edit view:

@MyApp.module "CrewApp.Edit", (Edit, App, Backbone, Marionette, $, _) ->    class Edit.Layout extends App.Views.Layout      template: "crew/edit/edit_layout"        regions:          titleRegion:    "#title-region"          formRegion:     "#form-region"          cityRegion:   "#city-region"    class Edit.Title extends App.Views.ItemView      template: "crew/edit/edit_title"        modelEvents:          "updated" : "render"    class Edit.Crew extends App.Views.ItemView      template: "crew/edit/edit_crew"  

Code for [popuplist] controller:

@MyApp.module "Components.Popuplist", (Popuplist, App, Backbone, Marionette, $, _) ->    class Popuplist.Controller extends App.Controllers.Base        initialize: (options={}) ->          @popuplist = App.request "city:entities"  ## actually tried hard-coding the city collection, but I know it's unnecessary           @popuplistView = @getPopuplistView options            getPopuplistView: (options = {})->            new Popuplist.Popuplist              config: options              collection: @popuplist    App.reqres.setHandler "popuplist:wrapper", (contentView, options={}) ->      popuplistController = new Popuplist.Controller          view: contentView          config: options      popuplistController.popuplistView  

Code for [popuplist] view:

@MyApp.module "Components.Popuplist", (Popuplist, App, Backbone, Marionette, $, _) ->  class Popuplist.PopuplistMember extends App.Views.ItemView      template: "popuplist/_popuplist_member"      tagName: "option"      className:  "popuplist-member"    class Popuplist.Empty extends App.Views.ItemView      template: "popuplist/_empty"      tagName: "option"    class Popuplist.Popuplist extends App.Views.CollectionView      template: "popuplist/_popuplist"      itemView: Popuplist.PopuplistMember ## ItemView is defined here !!!      emptyView: Popuplist.Empty      itemViewContainer: "select"      tagName: "select"  

Template for [_popuplist.jst.eco]:

<select class="selector"> </select>  

Template for [_popuplist_member.jst.eco]:

<option value= <%=@id %> >   <%= @name %>  </option>  

Any help, will be appreciated!

Pull changes from github to local rails files

Posted: 23 Jul 2016 07:47 AM PDT

So I know how to update the repository with my files (the master one at least). And I know I can create a local branch with

$ git checkout -b [branch_name]  

but that only creates it on the local git...how do i checkout a branch from the master on github and also overwrite files in my app directory, so I can update my project with the work of other people

How to create follower and followee in Rails?

Posted: 23 Jul 2016 07:29 AM PDT

I'm quite stuck in in Ruby on Rails relations and I really appreciate you help.

Have model User

class User < ActiveRecord::Base    has_many :followers, :through => :follows, foreign_key: "followee_id"    has_many :followees, :through => :follows, foreign_key: "follower_id"  end  

and model Follow

class Follow < ActiveRecord::Base    belongs_to :followee, class_name: "User"    belongs_to :follower, class_name: "User"  end  

but if want to create new follower like:

user.followers << User.first  

the result is SystemStackError

Thank you for every help!

How to connect a Rails App on one server (DigitalOcean droplet) to a MongoDB server on another server via private connection

Posted: 23 Jul 2016 07:00 AM PDT

I'm trying to setup two servers: one for my App and another for my DB (MongoDB).

Each server sits on its own droplet (VPS) and both servers can talk to each other via private network.

I want to completely close my db server off the internet and only allow connections from the private network.

I can connect to the server via ssh tunnel like so: ssh -L 4321:localhost:27017 -i ~/.ssh/id_rsa.pub myuser@myserver_ip but how can I configure Rails/Mongoid to connect to the server the same way (using the private network rather than connect via internet)?

Is it at all possible?

how to get facebook canvas application analytics for events?

Posted: 23 Jul 2016 07:03 AM PDT

I am developing "Facebook Canvas Application" using RubyonRails(Ruby-2.2.4), and also i have used "JS sdk" for login, using that can i be able to get the events analytics?Does any one know about it, please help me out.

Stripe::InvalidRequestError in ChargesController#create

Posted: 23 Jul 2016 07:22 AM PDT

I am using stripe within my app. When I click on the payment button, I get an error:

Stripe::InvalidRequestError in ChargesController#create    Invalid source object: must be a dictionary or a non-empty string. See API docs at https://stripe.com/docs'    @amount = 100  customer = Stripe::Customer.create(    :email => params[:stripeEmail],    :source  => params[:stripeToken]  )  

To make it work, I need to refresh the page; then everything works fine. So I went ahead and added no-turbo-link to the div like so:

<div data-no-turbolink="true" class="paymentsection">  </div>  

But I still need to refresh for it to work.

cannot load Java class java_prog.Continuation

Posted: 23 Jul 2016 04:57 AM PDT

I have a java program that consists of several class and interface files that i compiled and put under a package called java_prog . And then i created a .jar file in order to call that package in my jruby on rails application.

i made a simple controller that i call a class from that package to see if its working but it can't find the class

class WebhookController < ApplicationController    skip_before_action :verify_authenticity_token      require "java"    require "javaprog.jar"    java_import "java_prog.Continuation"      def check      Java::java_prog::Continuation.main([])    end      end  

I should also say that when compiling the .java files i referenced to some lib folder that has some .jar files. Do i need to include a folder called lib in the package itself before making a jar and maybe that is why its not working?

Part of Continuation class

package java_prog;    import java.util.Random;  import java.util.Arrays;  import java.util.List;  import java.util.ArrayList;  import java.lang.*;  //package org.apache.commons.lang.ArrayUtils;  //import org.apache.commons.lang3.ArrayUtils;  import java.io.*;  import Jama.*;  // NetLogo libraries  import org.nlogo.api.LogoList;  import org.nlogo.api.Turtle;  import org.nlogo.headless.HeadlessWorkspace;    public class Continuation extends ContinuationParameters  {        public static void main (String[] args) {          long startTime = System.currentTimeMillis();         ....    }  

any insight very welcomed!

Can't get uniqueness validation test pass with shoulda matchers

Posted: 23 Jul 2016 05:30 AM PDT

I have a shoulda matcher in my achievement_spec.rb and I can't get it pass:

Spec:

- require 'rails_helper'      RSpec.describe Achievement, type: :model do       describe 'validations' do        it { should validate_presence_of(:title) }       it { should validate_uniqueness_of(:title).case_insensitive.scoped_to(:user_id).with_message("you     can't have two achievements with same title")}           it { should validate_presence_of(:user) }        it { should belong_to(:user) }   end   end  

Model:

- class Achievement < ActiveRecord::Base    belongs_to :user        validates :title, presence: true      validates :user, presence: true           validates :title, uniqueness: {          scope: :user_id,                  message: "you can't have two achievements with the same title"    }           enum privacy: [ :public_access, :private_access, :friends_access ]         def description_html         Redcarpet::Markdown.new(Redcarpet::Render::HTML).render(description)   end  end  

Error:

- .F..       Failures:         1) Achievement validations should validate that :title is     case-sensitively unique within the scope of :user_id, producing a     custom validation error on failure          Failure/Error: it { should validate_uniqueness_of(:title).scoped_to(:user_id).with_message("you     can't have two achievements with same title") }              Achievement did not properly validate that :title is case-sensitively            unique within the scope of :user_id, producing a custom validation error            on failure.              After taking the given Achievement, setting its :title to ‹"an              arbitrary value"›, and saving it as the existing record, then making a              new Achievement and setting its :title to ‹"an arbitrary value"› as              well and its :user_id to a different value, ‹nil›, the matcher              expected the new Achievement to be invalid and to produce the              validation error "you can't have two achievements with same title" on              :title. The record was indeed invalid, but it produced these              validation errors instead:                * user: ["can't be blank"]              * title: ["you can't have two achievements with the same title"]          # ./spec/models/achievement_spec.rb:29:in `block (3 levels) in <top (required)>'       Finished in 0.16555 seconds (files took 3.13 seconds to load) 4     examples, 1 failure       Failed examples:       rspec ./spec/models/achievement_spec.rb:29 # Achievement validations     should validate that :title is case-sensitively unique within the     scope of :user_id, producing a custom validation error on failure       [Finished in 4.1s with exit code 1] [cmd: ['rspec', '-I     /home/mayur/Downloads/MyWork/ruby/i-rock/spec/models',     '/home/mayur/Downloads/MyWork/ruby/i-rock/spec/models/achievement_spec.rb']]     [dir: /home/mayur/Downloads/MyWork/ruby/i-rock] [path:     /usr/local/rvm/gems/ruby-2.2.4/bin:/usr/local/rvm/gems/ruby-2.2.4@global/bin:/usr/local/rvm/rubies/ruby-2.2.4/bin:/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/usr/local/rvm/bin:/home/mayur/.local/bin:/home/mayur/bin]  

How can I get rid of above error?

I tried below solution but getting same error:

Change in model:

validates :title, uniqueness: {          case_sensitive: false,          scope: :user_id,           message: "you can't have two achievements with the same title"      }  

Change in spec:

it { should validate_uniqueness_of(:title).case_insensitive.scoped_to(:user_id).with_message("you can't have two achievements with same title") }  

Error Again:

.F..    Failures:      1) Achievement validations should validate that :title is case-insensitively unique within the scope of :user_id, producing a custom validation error on failure       Failure/Error: it { should validate_uniqueness_of(:title).case_insensitive.scoped_to(:user_id).with_message("you can't have two achievements with same title") }           Achievement did not properly validate that :title is case-insensitively         unique within the scope of :user_id, producing a custom validation error         on failure.           After taking the given Achievement, setting its :title to ‹"an           arbitrary value"›, and saving it as the existing record, then making a           new Achievement and setting its :title to ‹"an arbitrary value"› as           well and its :user_id to a different value, ‹nil›, the matcher           expected the new Achievement to be invalid and to produce the           validation error "you can't have two achievements with same title" on           :title. The record was indeed invalid, but it produced these           validation errors instead:             * user: ["can't be blank"]           * title: ["you can't have two achievements with the same title"]       # ./spec/models/achievement_spec.rb:29:in `block (3 levels) in <top (required)>'    Finished in 0.13566 seconds (files took 3.14 seconds to load)  4 examples, 1 failure    Failed examples:    rspec ./spec/models/achievement_spec.rb:29 # Achievement validations should validate that :title is case-insensitively unique within the scope of :user_id, producing a custom validation error on failure  

How to change default path/url in routes in Rails 4

Posted: 23 Jul 2016 06:50 AM PDT

I'm working on a simple reservation application. Here are my routes

resources :users do    get 'reservations', on: :member  end    resources :listings do    resources :reservations  end  

When I try to make a reservation, action reservations#new takes me to reservations_path . Of course I'm getting error as this path doesn't exist. I'd like action new to take me to listing_reservations_path instead. I was hopping it will be done automatically since resources :reservations is in nested resources. I read about routes and tried many things but can't find any working way of doing it. Is it possible?

Simple form association has conflict with default input class

Posted: 23 Jul 2016 07:42 AM PDT

I have a simple form. Everything worked fairly okey until I came to the point I wanted to add an association form. The association itself works fine so I'll skip that. Saving data works. The issue lays in the control of the input class in exceptions.

<%= simple_form_for @fabmoment do |f| %>        	    <%= f.input_field :title %>    <%= f.label :title %>    <%= f.error :title %>    <%= f.input_field :description, rows: 7 %>    <%= f.label :description %>    <%= f.error :description %><br><br>    <%= f.association :machines, as: :check_boxes,                                  :label_method => lambda { |m| " #{m.name}" } %>        <% end %>

As you see I am very specific in where I put what, and this is because of my CSS library (W3.CSS). The problem is that in my initializer I put the class of "w3-input" as the default for inputs. But this doesn't work for my association checkboxes. At the moment I see that the label and input checkbox are not inline.

This wouldn't be the case if the "w3-input" class wouldn't be there. But I can't remove it, I can only go as deep as the item_wrapper_tag and the item_wrapper_class.

This his highly annoying. I have been busy with this for hours yesterday.

Why can't I do something like this:

<%= f.association :machines, as: :check_boxes do |m| %>      <%= m.check_box :machine_id, class: 'w3-check' %>    <%= m.label :name, class: 'w3-validate' %>    <% end %>

Get zoho emails in my rails application

Posted: 23 Jul 2016 04:22 AM PDT

I am trying to fetch emails received and sent from zoho account. I want to trace all the emails coming to me in outlook or I am sending from outlook.

I have seen zohoCRM, rubyzoho but not able to get things done. Any suggestions on this.

Put alert on top of main div

Posted: 23 Jul 2016 07:55 AM PDT

In my rails app my flash alerts dont display correctly : enter image description here

I have tried to put a z-index on my alert class but it doesnt work. Here's the way I organize my code in the app. I render the alerts in the layout :

  <%= render 'shared/navbar'%>   <%= render 'shared/flashes' %>    <%= yield %>    </body>  

and here's my html in slim for the flashes :

- if notice    div class="alert alert-info alert-dismissible" id="alert" role="alert"      div class="container"        div class="row"          div class="col-xs-12"            button type="button" class="close" data-dismiss="alert" aria-label="Close"              span aria-hidden="true" &times;            = notice.html_safe    - if alert      div class="alert alert-warning alert-dismissible" id="alert" role="alert"        div class="container"          div class="row"            div class="col-xs-12"              button type="button" class="close" data-dismiss="alert" aria-label="Close"                span aria-hidden="true" &times;              = alert.html_safe  

maybe I should also change my class background-cover which wraps my home page that you see ?

.background-cover {    background-position: center;    background-image: linear-gradient(135deg, rgba(0,0,0,0.8) 0%, rgba(0,0,0,0.2) 50%), image-url("hands.jpg");    background-size: cover;    text-align: center;    color: white;    min-height: 661px;  }  

Here's my home page html :

<div class="background-cover">    <div class="row text-center quickbed">      <h1 class="title">Quickbed</h1>      <p class="punchline">Se sentir chez soi est un droit</p>    </div>    <div class="row options">      <div class="col-sm-6">        <div class="card card-block  text-center">          <h3 class="card-title option-title ">Hotel d'hébergement social</h3>          <p class="card-text">Par ici si vous souhaitez accueillir des réfugiés.</p>          <%= link_to "S'inscrire", "#", class: "btn btn-success btn-lg js-subscription-form" %>        </div>      </div>      <div class="col-sm-6">        <div class="card card-block text-center">          <h3 class="card-title option-title">Association volontaire</h3>          <p class="card-text">Par ici si vous faites parti d'une association aidant les réfugiés à trouver un logement.</p>          <%= link_to "S'inscrire", "#", class: "btn btn-success btn-lg js-subscription-form" %>        </div>      </div>    </div>  </div>    <div class="row" id="story">      <h2 class= "text-center">Why Quickbed ?</h2>      <h3 class="text-center"> For you Super helper</h3>      <div class="col-xs-4 text-center">Find quickly a bed</div>      <div class="col-xs-4 text-center">Find Cheapest price</div>      <div class="col-xs-4 text-center">Manage your bills easily</div>    </div>    <div class="row">     <h3 class="text-center"> For you nice host</h3>      <div class="col-xs-4 text-center">Simplify your process</div>      <div class="col-xs-4 text-center">Manage your team</div>      <div class="col-xs-4 text-center">Optimise your space</div>    </div>    <div class="row" id="subscription_form">        <h3 class="text-center">Soyez premier à tester !</h3>      <div class="col-xs-offset-4 col-xs-4">        <%= simple_form_for @user, url: users_path do |f| %>          <%= f.error_notification %>          <div class="form-group">            <%= f.input :first_name, label: "Prénom", class: "form-control", placeholder: "Jean"%>          </div>          <div class="form-group">            <%= f.input :last_name, label: "Nom", class: "form-control", placeholder: "Dupond" %>          </div>          <div class="form-group">            <%= f.input :email, label: "Email", class: "form-control", placeholder: "dupond@gmail.com" %>          </div>          <div class="form-group">            <%= f.input :organisation, label: "Organisation", class: "form-control", placeholder: "Samu Social" %>          </div>          <div class="form-group">            <%= f.input :organisation_type, label: "Type d'Organisation", class: "form-control" %>          </div>          <div class="form-group">            <%= f.submit "Valider", class: "btn large_btn btn-success" %>          </div>        <% end -%>      </div>    </div>  </div>  

Can you show me how to make the alert come on top of the main div and explain how to do that.

How to fetch account email using Outlook REST API?

Posted: 23 Jul 2016 06:59 AM PDT

There is outdated tutorial in Ruby - https://dev.outlook.com/restapi/tutorial/ruby ( search for get_email_from_id_token in the .\o365-tutorial\app\helpers\auth_helper.rb file )

First of all - I tried it and it does not work.

I tried to make request for profile:

conn = Faraday.new(url: 'https://outlook.office.com') do |faraday|    # Outputs to the console    faraday.response :logger    # Uses the default Net::HTTP adapter    faraday.adapter  Faraday.default_adapter  end    response = conn.get do |request|    # Get events from the calendar    request.url '/api/v2.0/Me'    request.headers['Authorization'] = "Bearer #{token}"    request.headers['Accept'] = 'application/json'  end    JSON.parse(response.body)  

It returns user profile data, but email field is blank. It is strange.

Did anyone face/solve this problem ?

bin/rails Permission Denied

Posted: 23 Jul 2016 04:15 AM PDT

First Rails setup, following this guide http://guides.rubyonrails.org/getting_started.html

tried creating a controller with bin/rails generate controller Welcome index

I got -bash: bin/rails: Permission denied

Had a little google and found i should run chmod u+x bin/rails and even chmod a+x bin/rails to make the rails file executable

I ran this at the root of my brand new rails directory, and tried running the generate controller command again and still the same Permission denied error.

Ive tried completely deleting the directory and creating another rails project too, but this did the same thing

ruby 2.2.2 rails 5.0.0

How is work done by a physical Web server when a Web application is running on it?

Posted: 23 Jul 2016 02:59 AM PDT

I want to better understand how work is done by a physical Web server (i.e. the machine) when a Web application (web server + webframework) is running on it, the distinction between the different processes/threads running on the physical web server and how they interact with one another.

If I have a physical web server and boot up a software web server, say Puma, is that just one process continually running on the server?

When a user makes a request to the (software) web server:

  • how is the code for the controller in the web framework called? (I'm using Rails if that makes any difference). I mean is it already a part of the process that's already running, or is it somehow called separately?

  • does that spawn a new process (or thread?)? If so, is there any limit to how many of these processes/threads will be spawned as multiple users make requests?

  • what if the controller itself spawns new threads or processes? Would the software web server have any knowledge of this? If not,would that mean any limit could be breached?

  • if a controller kicks off a background process, how can any data returned by the background process be used the next time the user connects to the Web app? Can the variables be picked up, or would the data have to be stored somewhere like a database?

  • if I wanted to write my own job queuing system, where should I write the code, how would I launch it, and how would I send jobs to it and then pick up the output? Again, could I pick up the actual objects returned, or would I have to store them as data somewhere and recreate the objects?

Clearly I am a total novice at this stuff, so my assumptions may be wrong, and please just ask if you need clarification.

Check current page from controller in Rails?

Posted: 23 Jul 2016 07:20 AM PDT

Is there a way to check the current page from the controller? I tried current_page? but that returns a undefined method 'current_page?' error.

Why does this code not give expected output?

Posted: 23 Jul 2016 07:25 AM PDT

I was experimenting with database operations. For example,

begin     db_con = PG.connect :dbname => 'sureshkumar', :user => 'sureshkumar'     db_con.prepare 'get_result', "SELECT * from users;"     users_name = db_con.exec_prepared 'get_result'     if users_name != nil         puts users_name.values     else         puts "There is no users available in the table users"     end  rescue PG::Error => e          puts e.message  ensure          db_con.close if db_con  end  

The table users contains only two columns. They are,

user_id  user_name  

If the table does not contain any row, the exec_prepared statement does not return any row. In this case, why does the if condition not become false? How do I check if the exec_prepared method doesn't return any row?

Payola gem with Stripe - Updating payola_subscription table

Posted: 23 Jul 2016 02:14 AM PDT

I just started looking at the payola gem and having an issue. The gem creates a table called payola_subscription, which is supposed to record subscription creation, cancellation, etc. So far, when I create a new subscription, it is recorded in this table, but when I cancel a subscription, this table does not get updated. My question is: Is payola gem supposed to update records on this table if actions such as cancel subscription are performed, or I have to implement these manually in my cancel method? Strange thing (for me) is that Payola::UpdateCard.call used in the card_update method updates the database with the new credit card number, but Payola::CancelSubscription.call does not update the table. Below is the controller code for canceling subscriptions. What am I overlooking or doing wrong?

# subscriptions_controller.rb  class SubscriptionsController < ApplicationController    include Payola::StatusBehavior      def create      owner = current_user # this is just an example for Devise      # set your plan in the params hash      params[:plan] = SubscriptionPlan.find_by(id: params[:plan_id])      # call Payola::CreateSubscription      subscription = Payola::CreateSubscription.call(params, owner)      current_user.subscription_plan_id=params[:plan_id]      current_user.save      flash.notice = "Subscription successfully created"      UserMailer.subscribe_email(current_user).deliver_now      render_payola_status(subscription)    end      def cancel      if params[:guid].present?         @subscription = Payola::Subscription.find_by(:guid => params[:guid])         Payola::CancelSubscription.call(@subscription) if !@subscription.nil?         current_user.subscription_plan_id=nil         current_user.save         UserMailer.unsubscribe_email(current_user).deliver_now         flash.notice = "Subscription successfully cancelled"         redirect_to dashboard_path      end    end      def card_update        @subscription = Payola::Subscription.find_by!(guid: params[:guid])        Payola::UpdateCard.call(@subscription, params[:stripeToken])        flash.notice = "Your credit card successfully updated!"        render_payola_status(@subscription)    end    end  

Modifying the appearance of file upload buttons in ruby on rails or CSS

Posted: 23 Jul 2016 01:56 AM PDT

The title says it all. How do you go about doing this? For example, editing the width of a file upload button results in this: http://i.imgur.com/jacnps2.png For comparison, here's an ordinary file upload button: http://i.imgur.com/tIy05HA.png

The red rectangle represents the area the button normally takes up. In addition, when you hover your cursor over that spot (except for where the red and blue rectangles overlap), your cursor will transform into a hand icon, indicating that something will happen when you click that area. However, nothing happens.

The blue rectangle represents what portion of the screen you can click (which is mostly invisible, and much smaller than usual) to make the file upload form appear.

Trying to edit the file upload button's height yields similar results, only vertically instead of horizontally.

For the sake of explaining what my goal is: I'd like to overly a transparent or invisible file upload button on top of user avatars on my website. So far I've pulled off the easy parts, making the file upload button transparent and overlaying it on top of a user's avatar, but I haven't figured out how to edit the usable dimensions of the file upload button. For a working example of this, if you have a facebook profile, go to your profile and hover your mouse over your avatar. The words "Update Profile Picture" will appear and you can click them to edit your avatar directly from your profile instead of having to go to a separate settings page.

Rails with_lock on table with primary key as id and created_at

Posted: 23 Jul 2016 03:03 AM PDT

I have a model which initially had primary key constrain on column id

test_row = Test.find_by_code(code)  test_row.with_lock do      // Write logic  end  

This used to work but now due to table partitioning we have introduced primary key constraints on id and created_at. Ever since, the with_lock block is failing with the following error:

ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'test.' in 'where clause': SELECT  `test`.* FROM `test`  WHERE `test`.`` = 274361969 LIMIT 1 FOR UPDATE  

Please suggest correct way to do this. I only want to achieve row level lock.

PG::InvalidDatetimeFormat Error in Ruby

Posted: 23 Jul 2016 02:02 AM PDT

Script:

require 'pg'    con = PGconn.connect(:dbname => 'employee');  con.exec "SET datestyle TO DMY"    con.prepare 'getid' , "SELECT id FROM users WHERE user = $1 AND date IN ($2)"    str = "'21/07/2016' , '22/07/2016'"  res = con.exec_prepared 'getid' , ['usr1',str]  puts res.values  

Output:

g.rb:10:in `exec_prepared': ERROR:  invalid input syntax for type date: "'21/07/2016' , '22/07/2016'" (PG::InvalidDatetimeFormat) from g.rb:10:in `<main>'  

My requirement is to get all the id's based on user name and date. But it gives the above error. How to solve this ?

Get input value using htmlfor

Posted: 23 Jul 2016 01:14 AM PDT

What's the best way to accomplish something like this:

html.erb

<!-- inside a loop -->      <i htmlfor="wish">          <!-- name or icon -->      </i>      <input type="hidden" class="wish-cls" name="wish" value="<%= product.id %>" />  <!-- end loop -->  

JavaScript

$(".wish").click(function(e){    e.preventDefault();    //var id = document.getElementsByTagName('wish-cls');    console.log("Clicked: " + e.target.value);  });  

If I click the input, when not hidden, I get the value but how to achieve this using htmlfor? Is it possible?

Rails javan/whenever is running cron jobs as root

Posted: 23 Jul 2016 12:49 AM PDT

I have a Nginx + Passenger + Rails running on port 80, which requires starting nginx with sudo. Now when I go to use whenever, it is also being run as sudo. How do I avoid this?

Here is my logs from log/cron/error.log:

Ignoring bcrypt-3.1.10 because its extensions are not built.  Try: gem pristine bcrypt --version 3.1.10  Ignoring bcrypt-ruby-3.0.1 because its extensions are not built.  Try: gem pristine bcrypt-ruby --version 3.0.1  Ignoring bigdecimal-1.2.7 because its extensions are not built.  Try: gem pristine bigdecimal --version 1.2.7  Ignoring binding_of_caller-0.7.2 because its extensions are not built.  Try: gem pristine binding_of_caller --version 0.7.2  /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/spec_set.rb:92:in `block in materialize': Could not find rake-11.2.2 in any of the sources (Bundler::GemNotFound)      from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/spec_set.rb:85:in `map!'      from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/spec_set.rb:85:in `materialize'      from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/definition.rb:140:in `specs'      from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/definition.rb:185:in `specs_for'      from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/definition.rb:174:in `requested_specs'      from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/environment.rb:18:in `requested_specs'      from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/runtime.rb:13:in `setup'      from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler.rb:127:in `setup'      from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/setup.rb:18:in `<top (required)>'      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:128:in `require'      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:128:in `rescue in require'      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:39:in `require'      from /Users/Passa/Documents/project/config/boot.rb:6:in `<top (required)>'      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'      from script/rails:5:in `<main>'  

I have tried running the cron job manually that whenever produces:

/bin/bash -l -c 'cd /Users/Passa/Documents/project && script/rails runner -e development '\''Subscription.renew_user_bandwidth'\'' >> log/cron/cron.log 2>> log/cron/error.log'  

but end up getting this error:

Ignoring bcrypt-3.1.11 because its extensions are not built.  Try: gem pristine bcrypt --version 3.1.11  Ignoring bigdecimal-1.2.7 because its extensions are not built.  Try: gem pristine bigdecimal --version 1.2.7  /Users/Passa/.rvm/gems/ruby-2.2.2@divshare-v2/gems/bundler-1.12.5/lib/bundler/spec_set.rb:95:in `block in materialize': Could not find libv8-3.16.14.15 in any of the sources (Bundler::GemNotFound)      from /Users/Passa/.rvm/gems/ruby-2.2.2@divshare-v2/gems/bundler-1.12.5/lib/bundler/spec_set.rb:88:in `map!'      from /Users/Passa/.rvm/gems/ruby-2.2.2@divshare-v2/gems/bundler-1.12.5/lib/bundler/spec_set.rb:88:in `materialize'      from /Users/Passa/.rvm/gems/ruby-2.2.2@divshare-v2/gems/bundler-1.12.5/lib/bundler/definition.rb:140:in `specs'      from /Users/Passa/.rvm/gems/ruby-2.2.2@divshare-v2/gems/bundler-1.12.5/lib/bundler/definition.rb:185:in `specs_for'      from /Users/Passa/.rvm/gems/ruby-2.2.2@divshare-v2/gems/bundler-1.12.5/lib/bundler/definition.rb:174:in `requested_specs'      from /Users/Passa/.rvm/gems/ruby-2.2.2@divshare-v2/gems/bundler-1.12.5/lib/bundler/environment.rb:19:in `requested_specs'      from /Users/Passa/.rvm/gems/ruby-2.2.2@divshare-v2/gems/bundler-1.12.5/lib/bundler/runtime.rb:14:in `setup'      from /Users/Passa/.rvm/gems/ruby-2.2.2@divshare-v2/gems/bundler-1.12.5/lib/bundler.rb:95:in `setup'      from /Users/Passa/.rvm/gems/ruby-2.2.2@divshare-v2/gems/bundler-1.12.5/lib/bundler/setup.rb:19:in `<top (required)>'      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:128:in `require'      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:128:in `rescue in require'      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:39:in `require'      from /Users/Passa/Documents/project/config/boot.rb:6:in `<top (required)>'      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'      from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'      from script/rails:5:in `<main>'  

C:/Ruby22-x64/bin/rake: No such file or directory - mysql

Posted: 23 Jul 2016 12:10 AM PDT

I have migrated from sqlite3 db to mysql2 in RoR. There is a problem in migrating data to db. when i try to execute "rake db:reset", i get the following errors

C:/Ruby22-x64/bin/rake: No such file or directory - mysql --user\=root --passwor d\=root --host\=localhost --execute\=DROP\ DATABASE\ IF\ EXISTS\ `vice` rake aborted! NoMethodError: undefined method `exitstatus' for nil:NilClass

Tasks: TOP => db:reset => db:drop (See full trace by running task with --trace)

Gemfile

source 'https://rubygems.org'    gem 'rails', '~> 5.0.0'    gem 'mysql2'    gem 'puma'      gem 'uglifier', '>= 1.3.0'    gem 'jsonapi-resources' , github: 'cerebris/jsonapi-resources' ,branch: 'master'    gem 'sequel-rails'    gem 'carrierwave', github: 'carrierwaveuploader/carrierwave'    gem 'carrierwave-sequel' ,  require: 'carrierwave/sequel'    gem 'mini_magick'  gem 'devise_token_auth' , github: 'lynndylanhurley/devise_token_auth' , branch: 'master'    gem 'sequel-devise'    gem 'sequel-devise-generators'    gem  'sequel_simple_callbacks'      gem 'rack-cors'      group :development, :test do     gem 'byebug'   end    group :development do         gem 'web-console', '~> 3.0'       gem 'listen', '~> 3.0.5'         gem 'spring'       gem 'spring-watcher-listen', '~> 2.0.0'  end        gem 'sequel_enum'  

I am Using mongodb in rails and when use the carrierwave gem this thrown errors

Posted: 23 Jul 2016 12:44 AM PDT

I am using the following commond

gem 'carrierwave'

bundle

rails generate uploader image

mount_uploader :image, ImageUploader

but it gives the errors

NoMethodError in PostsController#index

undefined method `mount_uploader' for Post:Class Extracted source (around line #8):

line #8: mount_uploader :image, ImageUploader

end

Ruby on Rails ERR_TOO_MANY_REDIRECTS error for a given user role

Posted: 23 Jul 2016 07:48 AM PDT

I am a beginner to Ruby on Rails and this is an ruby on rails that was developed by someone.

There are 2 types of users: registered user with "user" role and registered user with "admin" role.

This too many redirects only happens if the user's role = "user", but not so if the user is "admin". I haven't figure out why yet.

First, if the user is the admin, I will get this in the log:

Started GET "/" for ::1 at 2016-07-22 18:18:17 -0700  Processing by ProductsController#home as HTML    ^[[1m^[[35mUser Load (0.1ms)^[[0m  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 11]]  controller_path: products  resource: product  method: product_params  after the parms setting => ${params}  Debugging in the Ability.rb...  User: #<User:0x007fe6d7f0f670>  user is admin    ^[[1m^[[36mProduct Load (0.3ms)^[[0m  ^[[1mSELECT "products".* FROM "products"^[[0m    ^[[1m^[[35mVersion Load (1.1ms)^[[0m  SELECT "versions".* FROM "versions"    ^[[1m^[[36mReltype Load (1.0ms)^[[0m  ^[[1mSELECT "reltypes".* FROM "reltypes"^[[0m  

and many more SQL statements; I would love to simplify that but that is a different question and another learning opportunity.

If the user is a regular user, the "redirect" will happen right after user is regular user

Started GET "/" for ::1 at 2016-07-22 18:25:23 -0700  Processing by ProductsController#home as HTML    ^[[1m^[[36mUser Load (0.1ms)^[[0m  ^[[1mSELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1^[[0m  [["id", 11]]  controller_path: products  resource: product  method: product_params  after the parms setting => ${params}  Debugging in the Ability.rb...  User: #<User:0x007fe6d13dca88>  user is regular user  Redirected to http://localhost:3000/  Completed 302 Found in 6ms (ActiveRecord: 0.1ms)      Started GET "/" for ::1 at 2016-07-22 18:25:23 -0700  Processing by ProductsController#home as HTML    ^[[1m^[[35mUser Load (0.1ms)^[[0m  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 11]]  controller_path: products  resource: product  method: product_params  ...repeat... for many more  

My guess is that the landing page is trying to pull all the data for use in this page and each SQL triggers a redirect... But first, I like to find why does it make a difference between an user with role user vs. role admin. I will worry about optimization later. Any help will be much appreciated.

Here is the config/routes.rb

Rails.application.routes.draw do    resources :groupings    resources :platforms    resources :versions    resources :reltypes    resources :products      # Devise stuff    devise_for :users    devise_scope :user do      get '/login' => 'devise/sessions#new'      get '/logout' => 'devise/sessions#destroy'    end      resources :users, :controller => "users"    unauthenticated :user do      resources :products, only: [:index, :show]      resources :versions, only: [:index, :show]      resources :reltypes, only: [:index, :show]      resources :platforms, only: [:index, :show]      resources :groupings, only: [:index, :show]    end      # You can have the root of your site routed with "root"    root to: 'products#home'      namespace :api, :defaults => {:format => :json} do      resources :platforms      resources :versions      resources :reltypes      resources :products      resources :groupings    end  end  

Next, controllers/application.rb

class ApplicationController < ActionController::Base    # include DeviseTokenAuth::Concerns::SetUserByToken    # Prevent CSRF attacks by raising an exception.    # For APIs, you may want to use :null_session instead.    protect_from_forgery with: :exception      # Devise: redirect to login page if user not logged in    before_action :authenticate_user!      before_filter do      resource = controller_path.singularize.to_sym      method = "#{resource}_params"      Rails.logger.debug("controller_path: #{controller_path}")      Rails.logger.debug("resource: #{resource}")      Rails.logger.debug("method: #{method}")        params[resource] &&= send(method) if respond_to?(method, true)    end      protected      def configure_permitted_parameters      devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:email, :password, :password_confirmation, roles: [])}    end      # CanCan: if user authorization fails, catch and modify    check_authorization :unless => :devise_controller?      rescue_from CanCan::AccessDenied do |exception|      redirect_to root_url, :alert => exception.message    end  end  

Here is the models/user.rb

class User < ActiveRecord::Base    devise :database_authenticatable, :registerable,      :recoverable, :rememberable, :trackable, :validatable      before_save :default_values      def default_values    #    self.role ||= 'user'      self.role = "user"    end      def is?(requested_role)      self.role == requested_role    end  end  

Finally, I found this models/activity.rb (I tried to put some debugging statements here:

class Ability    include CanCan::Ability      def initialize(user)      # Define abilities for the passed in user here. For example:      #      user ||= User.new # guest user (not logged in)      Rails.logger.debug("Debugging in the Ability.rb...")      Rails.logger.debug("User: #{user}")        if user.is? "admin"        Rails.logger.debug("user is admin")        can :manage, :all      else        Rails.logger.debug("user is regular user")        can :read, :all      end    end  end  

Added the controllers/products_controller.rb (as suggested by Sri Vishnu Totakura). I skipped the code for update/destroy just to save a little space.

class ProductsController < ApplicationController    load_and_authorize_resource #for CanCan      before_action :set_product, only: [:show, :edit, :update, :destroy]      # GET /products    # GET /products.json    def index      @products = Product.all    end      def home      @products = Product.all      @versions = Version.all      @platforms = Platform.all      @reltypes = Reltype.all      @prevrels = Prevrel.all    end      # GET /products/1    # GET /products/1.json    def show    end      # GET /products/new    def new      # puts "params for new: "      # puts params      @product = Product.new    end      # GET /products/1/edit    def edit    end      # POST /products    # POST /products.json    def create      puts "params for create: "      puts params      @product = Product.new(product_params)        respond_to do |format|        if @product.save          format.html { redirect_to @product, notice: 'Product was successfully created.' }          format.json { render :show, status: :created, location: @product }        else          format.html { render :new }          format.json { render json: @product.errors, status: :unprocessable_entity }        end      end    end      def update       ...    end      def destroy       ...    end      private      # Use callbacks to share common setup or constraints between actions.      def set_product        @product = Product.find(params[:id])        @versions = @product.versions      end        # Never trust parameters from the scary internet, only allow the white list through.      def product_params        params.require(:product).permit(:name)      end  end  

Carrierwave on Rails with ActiveDirectory adds tmp folder in store_dir

Posted: 23 Jul 2016 12:33 AM PDT

I am trying to use carrierwave and it is uploading the file fine, but I wanted my mp4 file to be in the public/uploads directory. It adds it there, but put it into a tmp/some-weird-id folder. I want just the mp4 file in public/uploads. Is this possible? If so, how? I have tried editing the cache_dir, but it still adds that weird id folder.

Here is the code so far:

class VideoUploader < CarrierWave::Uploader::Base      # Include RMagick or MiniMagick support:    # include CarrierWave::RMagick    # include CarrierWave::MiniMagick      # Choose what kind of storage to use for this uploader:    storage :file    # storage :fog      def store_dir      "public/uploads"    end      def move_to_cache      true    end      def move_to_store      true    end  

Here is the controller

 def create      @file = params["video"][:file].original_filename      @temp_upload = Video.new({ :file => @file})   end  

How to have "current_user" (coded as `session[:user_id]`) show user email, instead of some weird code?

Posted: 23 Jul 2016 02:43 AM PDT

I followed a tutorial on Rails forms (login,logout). All went well except for this bit: Once a user has logged in, the bottom of the page should say "You are logged in as" followed by an email address, so it will say, for example, "You are logged in as Jane@aol.com". The line of code responsbile for this:

<p>You are logged in as: <%= @current_user %></p>

However, what I get instead is You are logged in as: #<User:000s500r00k000h0> (Not an exact copy)

For the life of me, I cannot figure out what that number is and why the user's email doesn't show up-nor where to begin troubleshooting:

current_user is defined in ApplicationController:

class ApplicationController < ActionController::Base protect_from_forgery with: :exception

def authentication_required if !logged_in? redirect_to login_path end end

def logged_in? !!current_user end

def current_user @current_user ||= begin User.find(session[:user_id]) if session[:user_id] end end helper_method :current_user end

The user_id ought to be the user's email. What did I miss?

Rails 5 Accessing Assets from Coffee Files

Posted: 22 Jul 2016 09:16 PM PDT

I'm trying to access an image from a coffee file. I can get it to work in development, but not production. The ruby on rails guide for doing this doesn't seem to work. In production digesting is interfering with the paths.

Section 2.3.3 of the page below is supposed to work: http://guides.rubyonrails.org/asset_pipeline.html

This is my code:

$(document).on 'turbolinks:load', ->    $('.ui.embed').embed({      source      : 'youtube',      id          : 'l5m3CW1oWg0',      placeholder : "<%= asset_path 'overlook4@2x.jpg' %>"    })  

The error from browser console:

Blockquote [Error] Failed to load resource: the server responded with a status of 404 (Not Found) http://yyyyy.com/assets/overlook4@2x.jpg

Notice there is no md5 appended to the jpeg file so it can't find the compiled file.

My question is what is the CORRECT fix for this? Would it be ok to turn off digests in production? I find that it breaks too much stuff.

5 comments:

  1. Good post. I learn something new and challenging on blogs I stumbleupon everyday. It's always useful to read content from other authors and practice a little something from their web show sites.

    ReplyDelete