Wednesday, November 23, 2016

angular 2 subscription class not found | Fixed issues

angular 2 subscription class not found | Fixed issues


angular 2 subscription class not found

Posted: 23 Nov 2016 07:44 AM PST

Very new to action cable and angular 2. I keep receiving this error, Subscription class not found: "MessagesChannel", when running the rails server. I am using ng2-cable to connect to my rails api.

I am using angular 2 on cordova

import { NgModule } from '@angular/core';  import { IonicApp, IonicModule } from 'ionic-angular';  import { MyApp } from './app.component';  import { HomePage } from '../pages/home/home';  import { MessageData } from '../providers/message-data';  import { Ng2Cable, Broadcaster } from 'ng2-cable/js/index';    @NgModule({    declarations: [      MyApp,      HomePage    ],    imports: [      IonicModule.forRoot(MyApp)    ],    bootstrap: [IonicApp],    entryComponents: [      MyApp,      HomePage    ],    providers: [ MessageData, Ng2Cable, Broadcaster ]  })  export class AppModule {    messages: any;    constructor(private ng2cable: Ng2Cable, private broadcaster:       Broadcaster){      this.ng2cable.subscribe('http://localhost:3000/cable',   'MessagesChannel');        }    }  

Rails MessagesChannel

class MessagesChannel < ApplicationCable::MessagesChannel    def subscribed      stream_from 'allmessages'    end  end  

Any help is appreciated!

String start with # return with backslash in rails console in some case

Posted: 23 Nov 2016 07:42 AM PST

In console of rails 4.2.7, I have the following test:

[45] pry(main)> '#$'  => "\#$"  [46] pry(main)> '#@'  => "\#@"  [47] pry(main)> '#!'  => "#!"  [48] pry(main)> '#ab'  => "#ab"  

It seems rails will only put a "\" before the string when there is an @ or $ after #.

The problem leads me to this test is that I have a erb file that render a data attribute with an array of json:

data-xx="<%= [{xx: '#$', yy: 'yy'}.to_json, {zz: 'zzz'}.to_json] %>"  

Then in chrome console, it will give the unexpected result as

$("#entry_show_modal_template").data('xx')  "["{\"xx\":\"\#$\",\"yy\":\"yy\"}", "{\"zz\":\"zzz\"}"]"  

And when I change xx value from #! or some other string, the result will be ok as an array

$("#entry_show_modal_template").data('xx')  ["{"xx":"#!","yy":"yy"}", "{"zz":"zzz"}"]  

Does someone know if it is true and why it has such difference? And it there any way to tackle this problem?

Rails 4 Spree Invoke callback "Undefined method for User xxxxx"

Posted: 23 Nov 2016 06:51 AM PST

I want to use callbacks to modify the admin product controller to create a listing for each user. Using decorator in spree product model I added the "belongs_to :user" relation. In my custom user model I added the "has_many :products" relation and also added product_id and index product_id to my user data table. I have this:

Spree::Admin::ProductsController.class_eval do  create.before :user_products    private     def user_products      @user.objects.build params[object_name]   end  end   

object_name is a function inherited from ResourceController. It returns a string containing current object name "product".

But it is not working. I am getting "undefined method objects for User XXXXX" Looks like my association is not working. What am I doing wrong? Thanks in advance.

Javascript browser console error 404 (Not Found)

Posted: 23 Nov 2016 07:27 AM PST

I have my javascript created in the directory :

App / assets / javascript / product / products.js

In my Haml index.html.haml file, I've included this code to reference my js.file:

= javascript_include_tag 'products'

and also in config / application.rb I've included :

config.assets.precompile += ['products.js'].

However when my browser reloads, i get a red line error in the console showing

GET http://localhost:3000/javascripts/products.js 404 (Not Found) product:65.

Why is it getting from javascripts/products.js instead of going through the product directory file which i've put my script in there ?

In the script if I have the code alert, it gets triggered but if the codes are jquery, it won't run.

Create marker on mapbox with rails

Posted: 23 Nov 2016 07:02 AM PST

I want to create a dynamic map using Ruby on Rails, geojson, gem rgeo-geojson, and mapbox.js.

I have a form where users input a country with a select generated by a JSON file listing all the countries.

I want Rails to compare it with a countries.geo.json file listing all countries, and then generate a marker on the map with the country selected.

Here is my application_helper.rb where I create the select option form :

  def countries_for_select      file = File.read(Rails.root.join( 'app', 'helpers', 'countries.json'))      countries = JSON.parse(file)      countries.map {|c| [c['name']] }    end  

using countries.json file, and now I want to generate a marker on the map (mapbox) depending on which country user choose

My countries.json file is like that :

[      {          "name": "Afghanistan",          "code": "AF"      },      {          "name": "Ă…land Islands",          "code": "AX"      },  

Grant permission for the path

Posted: 23 Nov 2016 06:43 AM PST

I am following this guide, to install ruby, while everything has no problem except when I try to run this command

rails new myapp -d mysql

in which I got this error

  run  bundle install  There was an error while trying to write to  `/home/fil/.bundle/cache/compact_index/rubygems.org.443.29b0360b937aa4d161703e6160654e47`. It is likely that you need to  grant write permissions for that path.           run  bundle exec spring binstub --all  bundler: command not found: spring  Install missing gem executables with `bundle install`  

Is there any way to solve this?

Ruby on Rails with React getting NoMethodError

Posted: 23 Nov 2016 06:55 AM PST

The following is my controller Projects#show method.

def show      @project = Project.find(params[:id])      @pm = User.find(@project.user_id)      @employees = {}      @supervisors = User.all.where("id = ?", Relationship.all.where("supervisor_id = ?", @project.user_id).pluck(:supervisor_id))          @supervisor_ids = Relationship.all.where("supervisor_id = ?",   @project.user_id).pluck(:supervisor_id)      for supervisor in @supervisor_ids          @employees[supervisor] = User.all.where("id = ?", Relationship.all.where("supervisor_id = ?", supervisor).pluck(:employee_id))      end  end  

The following is my Projects#show view html.erb file.

<%= react_component 'ProjectManage', { pm: @pm, supervisors: @supervisors, employees: @employees } %>  

The following is my react front-end

@ProjectManage = React.createClass      getInitialState: ->        pm: @props.pm        render: ->        React.DOM.div          className: 'org-chart'          @props.pm.email        for supervisor in @props.supervisors          React.DOM.ul supervisor.email          for employee in @props.employees[supervisor]            React.DOM.li employee.email  

The error message I get is:

Completed 500 Internal Server error in ActiveRecord.

NoMethodError (undefined method ` ' for ProjectsController#show:0x007fa195b59da0

ANY HELP WOULD BE GREATLY APPRECIATED!!!

How to update a web page from requests made by another client (in rails)?

Posted: 23 Nov 2016 06:38 AM PST

Here is my need: I have to displays some information from a web page.
The web browser is actually on the same machine (localhost).
I want the data to be updated dynamically by the server initiative.

Since HTTP protocol is actually a request/response protocol, I know that to get this functionality, the connection between the server and the client (which is local here) should be kept open in some way (Websocket, Server-Sent Events, etc..)

Yes, "realtime" is really a fashion trend nowadays and there are many frameworks out there to do this (meteor, etc...)

And indeed, it seems that Rails supports this functionnality too in addition to using Websockets (Server-Sent Events in Rails 4 and ActionCable in Rails 5)
So achieving this functionnality would not be a big deal, I guess...

Nevertheless what I really want is to trigger an update of the webpage (displayed here locally) from a request made by another client..

This picture will explain that better :

Update from another client

  1. At the beginning, the browser connects to the (local) server (green arrows).
    I guess that a thread is executed where all the session data (instance variables) are stored.
    In order to use some "realtime" mechanisms, the connection remains open and therefore the thread Y is not terminated. (I guess this is how it works)
  2. A second user is connecting (blue arrows) to the server (could be or not be the same web page) and make some actions (eg. posting a form).
    Here the response to that external client does not matter. Just an HTTP OK response is fine. But a confirmation web page could also be returned.
    But in anyway the thread X (and/or the connection) has no particular reason to be kept.

Ok, here is my question (BTW thank you for reading me thus far).
How can I echo this new data on the local web browser ?

I see 2 differents ways to do this :

  • Path A: Before terminating, the thread X passes the data (its instance variables) to the thread Y which has its connection still open. Thus the server is able to update the web browser.
  • Path B: Before terminating the thread X sends a request (I mean a response since it is the server) directly to the web browser using a particular socket.

Which mechanisms should I use in either method to achieve this functionnality ?
For method A, how can I exchange data between threads ?
For method B, how can I use an already opened socket ?

But which of these two methods (or another one) is actually the best way to do that?

Again thank you for reading me thus far, and sorry for my bad english.
I hope I've been clear enough to expose my need.

How do I set up the Elasticsearch indices for this Rails 3.2 project I've inherited?

Posted: 23 Nov 2016 06:29 AM PST

I've just started working with a Rails 3.2 codebase which uses Elasticsearch via the elasticsearch-rails and elasticsearch-model gems. I've had a lot of difficulty getting this set up.

My understanding is that running, for example, User.import will create an index if none exists and then populate it with the records from the main database. However, I get an error trace that begins with the line [!!!] Index does not exist (Elasticsearch::Transport::Transport::Errors::NotFound).

I can copy the index structure from production manually, but I'm sure there must be a programmatic way to do it. I'll probably take more time scripting it than doing it myself, but I want to make this project easier to set up for future developers.

Am I missing an automatic way to import the indices themselves? Do I have to write such a script myself?

Thanks, Alexander

Tracking with google analytics sign up page in Rails with Devise

Posted: 23 Nov 2016 07:11 AM PST

I am trying to track each page of my Rails application, rendering this partial on the layout:

var analyticsId = '<%= Settings.env.app.analytics_id %>';    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;  i[r]=i[r]||function(){  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),  m=s.getElementsByTagName(o)[0];   a.async=1;a.src=g;m.parentNode.insertBefore(a,m)  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');    ga('create', '<%= Settings.env.app.analytics_id %>', 'auto', 'trackEvent: true');  ga('send', 'pageview');  

After adding the Google Analytics ID to the settings, I can see in my Google Analytics dashboard the visits to my users#sign_in page but not the visits to my users#sign_up page. Inspecting both pages through the firebug console I see the spected result in the html code:

var analyticsId = 'UA-XXXXXXXX-X';    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;  i[r]=i[r]||function(){  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g  m.parentNode.insertBefore(a,m)  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');      ga('create', 'UA-XXXXXXXX-X', 'auto', 'trackEvent: true');  ga('send', 'pageview');  

With 'UA-XXXXXXXX-X' = Settings.env.app.analytics_id which is defined in config/settings/app.yml under analytics_id.

We use devise to handle the signin/signup proccess and this is the part related to devise in the routes.rb

Rails.application.routes.draw do   devise_for :users, controllers: {    confirmations: 'users/confirmations',    registrations: 'users/registrations'   }   ActiveAdmin.routes(self)     authenticated :user do    devise_scope :user do     root to: redirect("/home")    end   end    unauthenticated do   devise_scope :user do     root to: redirect("users/sign_in"), as: "unauthenticated_index"     get '/pages/:page',    to: 'pages#show', as: "pages_show"   end  end  

Rails 4: How do I delete a nested object?

Posted: 23 Nov 2016 06:39 AM PST

So I have a user model and a nested model "Entries" like that:

user.rb

class User < ActiveRecord::Base      has_many :entries    ...    end  

entry.rb

class Entry < ActiveRecord::Base      belongs_to :user    ...    end  

user/show.html.erb

<p><%= link_to 'Destroy', remove_entry_path, method: :delete, data: { confirm: 'Are you sure?' } %></p>  

routes.rb

resources :users do      resources :entries  end  ...  delete "remove_entry" => "entries#destroy", :as => "remove_entry"  

entries_controller.rb

def destroy        @user = current_user      @user.entries.find(params[:id]).destroy        respond_to do |format|        format.html { redirect_to user_path(current_user), notice: 'Entry was successfully destroyed.' }        format.json { head :no_content }      end      end  

And I get this error:

Couldn't find Entry without an ID

on this line

@user.entries.find(params[:id]).destroy  

What am I doing wrong?

How can I Iterate through items and generate drag and drop buttons for each one?

Posted: 23 Nov 2016 06:07 AM PST

I'm very new to coding and I am experimenting with tools that are available. I am aware that my code is probably totally wrong but gave a guess as close as I could.

I am trying to iterate through items in the database and for each one I want a button to be created. The button should then be draggable by the user and saved in that position.

Does anyone know a way in which I could achieve this?

This is as far as I could get with my guess but it does not work. Also, I do not know how to save what the user does.

<% @item.each do |item| %>    <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>    <%= link_to item.name, item_path(item), id: "item", class: "btn btn-primary"%>      <div id="item" draggable="true" ondragstart="drag(event)"></div>    <% end %>    <script>  function allowDrop(ev) {   ev.preventDefault();  }    function drag(ev) {   ev.dataTransfer.setData("text", ev.target.id);  }    function drop(ev) {   ev.preventDefault();   var data = ev.dataTransfer.getData("text");   ev.target.appendChild(document.getElementById(data));  }  </script>  

Ruby on rails select tags from fixed lists(rails)

Posted: 23 Nov 2016 06:17 AM PST

I have some models, for example, Post, User. Is it possible to use tags only from fixed lists of tags for model Post and model User?

How to reverse an irreversible migration

Posted: 23 Nov 2016 05:19 AM PST

def self.down      # By default, we don't want to make any assumption about how to roll back a migration when your      # model already existed. Please edit below which fields you would like to remove in this migration.      raise ActiveRecord::IrreversibleMigration  end  

I have this in my devise migration, Now I have rollbacked the migration ..I got an error of

`StandardError: An error has occurred, this and all later migrations canceled:    ActiveRecord::IrreversibleMigration`  

Now I cannot access the model, even after rake db:migrate. How to make this work again?

Rails - validation inside decorator

Posted: 23 Nov 2016 05:49 AM PST

I'm struggling with some kind of issue. I have a rails model (mongoid).

class User    include Mongoid::Document    include ActiveModel::SecurePassword      validate :password_presence,             :password_confirmation_match,             :email_presence,      field :email    field :password_digest     def password_presence   end     def email_presence   end     def password_confirmation_match   end  end  

My goal is to call validations depends on which decorator I will use. Let's say I've got two decorators:

class PasswordDecorator < Draper::Decorator   def initialize(user)     @user = user   end  end    def RegistraionDecorator < Draper::Decorator    def initialize(user)     @user = user    end  end  

So now when I create/save/update my user object inside RegistraionDecorator I would like to perform all validation methods.

RegistraionDecorator.new(User.new(attrbiutes))  

But when I will do it inside PasswordDecorator I want to call for example only password_presence method.

PasswordDecorator.new(User.first)  

When I move validations to decorator it won't work cuz its different class than my model.

How can I achieve that?

Unable to load Bootstrap.min file

Posted: 23 Nov 2016 05:11 AM PST

I am trying to load bootstrap in my rails application. But it is not working. I had included the bootstrap and sass gems in my Gemfile. The following is my application.js file:

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

I have also tried using bootstrap-cdn but it did not solve my problem. And I am unable to load bootstrap.min file in the application.

Thanks in advance.

Ruby Active Record accessor dot(.) vs bracket([])

Posted: 23 Nov 2016 05:11 AM PST

With Active Record, we can access a value like

method access

user = User.find(1)  user.name #=> 'John'  

or

hash access

user[:name] #=> 'John'  

I just wonder when to use which, or is there any best practice out there? Personally I'd prefer method access because I feel that is more like ruby way. However when I see code by others, I face the hash access.

ignore Rack::Timeout middle in specific rails routes

Posted: 23 Nov 2016 04:47 AM PST

I have installed rack-timeout gem and created rack_timeout.rb inside the initializers.I have set Rack::Timeout.service_timeout = 1 inside rack_timeout.rb.I want to restrict the rack-timeout to halt the execution if timeout exceeded in controllers other than controllers inside api.Only the api controllers' execution should be stopped.I have created a custom middleware inside lib named my_middleware.rb

 class MyMiddleware < Rack::Timeout    def initialize(app, options = {})      @app = app      @exclude = options[:exclude]    end      def call(env)      if env['PATH_INFO'].include? "api"        super(env)      else        @app.call(env)      end    end  end  

config/development.rb

config.middleware.use "MyMiddleware"  

but its not working.everywhere rack timeout is throwing the exception when timeout happened.

How to achieve sequential processing in Rails?

Posted: 23 Nov 2016 07:42 AM PST

I have a task which has to be performed in sequential manner. It's mosty a database writing.

The problem is that I have hard time to achieve it in Rails 5.

I'm implementing it in an ActiveJob task. First I've tried mutex:

class EventLoadJob < ApplicationJob    MUTEX = Mutex.new      rescue_from(StandardError) do |exception|      puts exception.to_s    end      def perform      MUTEX.synchronize        SomeModel.new.save!      end    end  end  

But this causes deadlock. Let assume: one thread is inside critical section and other wait at critical section entry. So the first thread block on database query. It wait on the query forever. I suppose there iss problem with ActiveRecord thread/connection - it's somehow blocked. But why?

I've tried the same with locking on file:

class EventLoadJob < ApplicationJob    rescue_from(StandardError) do |exception|      puts exception.to_s    end      def perform      File.open(Rails.root.join('tmp', 'event_mutex'), File::RDWR|File::CREAT, 0644) do |file|        file.flock(File::LOCK_EX)        SomeModel.new.save!        file.flock(File::LOCK_UN)      end    end  end  

And I got the same strange behavior. I've tried the same in Controller instead of ActiveJob. The same: deadlock at ActiveRecord query.

Do you guys know a way to perform a task in sequential manner in Rails app? A proper way to create critical section?

Maybe there is ActiveJob queue adapter which is single threaded, without context switching, etc? I don't want to add redis or other stuff to my simple app.

Froala, Amazon S3, CORS, Error Message: No 'Access-Control-Allow-Origin' header is present on the requested resource

Posted: 23 Nov 2016 04:21 AM PST

I am using the Froala Editor to upload images to the Amazon S3 server using the imageUplaodToS3 option. I've seen a lot of posts that seem very similar to my post and I still can't figure out why I'm still having issues after reading them so I hope it doesnt get counted as an answered question. I feel like im very close but i get the following error in my console:

ERROR SCREENSHOT


It worked before but i'm not sure what i changed to make it not work again :(

My Amazon S3 CORS configuration is the following:

<?xml version="1.0" encoding="UTF-8"?>  <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">      <CORSRule>          <AllowedOrigin>http://localhost:3000</AllowedOrigin>          <AllowedMethod>GET</AllowedMethod>          <AllowedMethod>POST</AllowedMethod>          <AllowedMethod>PUT</AllowedMethod>          <MaxAgeSeconds>3000</MaxAgeSeconds>          <AllowedHeader>*</AllowedHeader>      </CORSRule>  </CORSConfiguration>  

Let me know if there's any other information I can help supply,

Thanks in advance!

How to get data which falls on specific days

Posted: 23 Nov 2016 04:20 AM PST

Hi I've start_date column which capture time stamp, I'd like to query the data based on days like if date falls on sunday or monday like that.

For example

from_date = Tue Nov 22 23:00:00 UTC 2016  to_date = Sun Nov 27 02:00:00 UTC 2016  

Here I need get all the records from tuesday 23:00 pm to sunday 02:00 am.

Paperclip Gem not loading file from Database on first try

Posted: 23 Nov 2016 05:01 AM PST

I have a website that allows a user to upload a file to a database using Paperclip gem. When on the dashboard I can click the download url, however when I click the link to open them it will occasionally redirect me to a 404 page saying the page could not be found, when I return to dashboard and try to display the file again it will then load and display in my browser, this sometimes needs to be repeated several times before the file will load. Question: how can I wait for the file to load before sending the response back to the page?

Rails - How to handle Model Templates

Posted: 23 Nov 2016 04:04 AM PST

Assume you have a relation of invoices and workpackages. An invoice can consist of more than one workpackage.

The tricky thing is that you can modify workpackages after adding to an invoice. That means that you have default workpackages you can select from (templates) and "real" workpackages that are assigned to an invoice.

How to handle this scenario in rails? I currently have two ideas:

  • Two separate tables, one called workpackage_template and one for workpackages. Everytime you assign a package to an invoice you copy to data from a workpackage_template to a workpackage and assign an invoice. (workpackages might have a reference to workpackage_template to avoid duplicate data like workpackage.description)
  • One table called workpackages and a template flag. Everytime you assign a package you copy a workpackage that has a template flag, remove the flag and add a invoice_id.

Downside of my first idea is that I have two tables that are almost identical, only the invoice_id is missing for the templates. Everytime you update one model you have to update both model, view, controllers.

Downside of the second idea is that templates and real packages are not completely separate, but do they have to be separate?

I would go with option 2 and the template flag, what's your opinion? Is there a best practice on how to deal with templates?

To be clear, I am sure that I can handle the problem, I not asking for a workaround or a somehow working solution, I am asking for the best practice if possible or experiences from other developers or maybe things I do not cover yet.

Gitlab CE not sending email

Posted: 23 Nov 2016 04:00 AM PST

I have setup Gitlab CE on a local Ubuntu Server, and I'm trying to use Zoho to send email to users. But, mails are not sent. Even when testing with gitlab-rails console :

irb(main):003:0> Notify.test_email('destination_email@address.com', 'Message Subject', 'Message Body').deliver_now  

My SMTP config is as follow :

gitlab_rails['smtp_enable'] = true  gitlab_rails['smtp_address'] = "smtp.zoho.com"  gitlab_rails['smtp_port'] = 587 # I've also changed to 465, but in vain  gitlab_rails['smtp_authentication'] = "plain"  gitlab_rails['smtp_enable_starttls_auto'] = true  gitlab_rails['smtp_user_name'] = "gitlab@mydomain.com"  gitlab_rails['smtp_password'] = "mypassword"  gitlab_rails['smtp_domain'] = "smtp.zoho.com"  

And Reply by email config :

gitlab_rails['incoming_email_enabled'] = true  gitlab_rails['incoming_email_address'] = "gitlab-incoming+{key}@domain.com"  gitlab_rails['incoming_email_email'] = "gitlab@domain.com"  gitlab_rails['incoming_email_password'] = "Password"  gitlab_rails['incoming_email_host'] = "imap.zoho.com"  gitlab_rails['incoming_email_port'] = 993  gitlab_rails['incoming_email_ssl'] = true  gitlab_rails['incoming_email_mailbox_name'] = "inbox"  gitlab_rails['incoming_email_idle_timeout'] = 60  

Can somebody help me fix this ?

Update : This is the output of the test in gitlab_rails console

Notify#test_email: processed outbound mail in 414.5ms

Sent mail to user@domain.com (65666.5ms) Date: Wed, 23 Nov 2016 12:47:12 +0100 From: GitLab Reply-To: GitLab

To: user@domain.com

Message-ID: <583581c03dae3_a7303fac34cdb0fc64a7@administrateur-virtual-machine.mail>

Subject: Test

Mime-Version: 1.0

Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: 7bit

Testons

Net::ReadTimeout: Net::ReadTimeout from /opt/gitlab/embedded/lib/ruby/2.3.0/net/protocol.rb:158:in rbuf_fill' from /opt/gitlab/embedded/lib/ruby/2.3.0/net/protocol.rb:136:inreaduntil' from /opt/gitlab/embedded/lib/ruby/2.3.0/net/protocol.rb:146:in readline' from /opt/gitlab/embedded/lib/ruby/2.3.0/net/smtp.rb:946:inrecv_response' from /opt/gitlab/embedded/lib/ruby/2.3.0/net/smtp.rb:556:in block in do_start' from /opt/gitlab/embedded/lib/ruby/2.3.0/net/smtp.rb:956:incritical' from /opt/gitlab/embedded/lib/ruby/2.3.0/net/smtp.rb:556:in do_start' from /opt/gitlab/embedded/lib/ruby/2.3.0/net/smtp.rb:521:instart' from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/mail-2.6.4/lib/mail/network/deli very_methods/smtp.rb:113:in deliver!' from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/mail-2.6.4/lib/mail/message.rb:2 149:indo_delivery' from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/mail-2.6.4/lib/mail/message.rb:2 37:in block in deliver' from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/actionmailer-4.2.7.1/lib/action_ mailer/base.rb:543:inblock in deliver_mail' from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/activesupport-4.2.7.1/lib/active _support/notifications.rb:164:in block in instrument' from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/activesupport-4.2.7.1/lib/active _support/notifications/instrumenter.rb:20:ininstrument' from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/activesupport-4.2.7.1/lib/active _support/notifications.rb:164:in instrument' from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/actionmailer-4.2.7.1/lib/action_ mailer/base.rb:541:indeliver_mail' from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/mail-2.6.4/lib/mail/message.rb:2 37:in deliver' from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/actionmailer-4.2.7.1/lib/action_ mailer/message_delivery.rb:85:indeliver_now' from (irb):1 from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/railties-4.2.7.1/lib/rails/comma nds/console.rb:110:in start' from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/railties-4.2.7.1/lib/rails/comma nds/console.rb:9:instart' from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/railties-4.2.7.1/lib/rails/comma nds/commands_tasks.rb:68:in console' from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/railties-4.2.7.1/lib/rails/comma nds/commands_tasks.rb:39:inrun_command!' from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/railties-4.2.7.1/lib/rails/comma nds.rb:17:in <top (required)>' from bin/rails:9:inrequire' from bin/rails:9:in `'

Rails search routing friendly URL

Posted: 23 Nov 2016 03:34 AM PST

I have found one example on this forum below link:

http://stackoverflow.com/a/14232632/4172515

This not enough for me, I have two input field form :location & :title like: params[:location] & params[:title] how can I handle this.

I have no idea how to do this.

How can I catch the log output of called submethods

Posted: 23 Nov 2016 03:23 AM PST

I am trying to debug a rake task (from an old Redmine v2 instance).

I made this task (source)

desc "switch rails logger to stdout"  task :verbose => [:environment] do    Rails.logger = Logger.new(STDOUT)  end    desc "switch rails logger log level to debug"  task :debug => [:environment, :verbose] do    Rails.logger.level = Logger::DEBUG  end  

and I run this task:

bundle exec rake debug redmine:email:receive_imap RAILS_ENV="production" host=xxx username=xxx password=xxx  

This does indeed give me some logging (in this case I get "Receiving message 106; Message 106 can not be processed"), but apparently only of the main rake task redmine:email:receive.

However, the log outputs of the called methods (like this one) are not shown.

Is there any trick to also catch the log outputs of called methods?

Controller's helper method on factory instance

Posted: 23 Nov 2016 07:01 AM PST

I have helper method "current_cart" in application controller:

 helper_method :current_cart    def current_cart      if !session[:cart_id].nil?          Cart.find(session[:cart_id])      else          Cart.new      end  end  

In line_item factory I try assign a value current cart to cart_id:

cart_id "#{current_cart}"  

Error:

"ArgumentError: Trait not registered: current_cart"  

What is the right way to use "current_cart" method in line_item factory?

Auth0 with Rails API

Posted: 23 Nov 2016 04:03 AM PST

I don't have a specific technical issue but a general problem understanding the architecture for using Auth0 for Authentication and then using the returned profile to access a rails API.

I am using Auth0.Lock in React Native and can successfully sign-up and login to my React Native App and store the returned profile and token.

On the Rails side I have create an API and setup Knock (https://github.com/nsarno/knock) as per the instructions to implement JWT Authentication.

What I don't understand is the link between my User model in Rails and my Database in Auth0. Neither the Auth0 documentation or the Knock documentation are clear on how this association happens.

Thanks Craig

Multiple levels has_many through queries on Rails 5

Posted: 23 Nov 2016 03:41 AM PST

First of all I have these 4 models:

Program:

has_many :fields_programs  has_many :fields, through: :fields_programs  

Fields:

has_many :fields_programs  has_many :programs, through: :fields_programs  

FieldsProgram:

belongs_to :program  belongs_to :field  

Entity:

has_many :programs  has_many :fields, -> {distinct}, through: :programs  

The issue here is that I'm trying to create a new scope for a search filter. I need to find entities based on their fields and I'm a little bit confused since there is two 'has_many through' relationships to get there. How can I achieve that ? Do I need to use Arel?

This is what I'm working on for now but obviously it doesn't work

scope :with_field_id, lambda { |field_id|      joins(:programs).where(programs: {fields_program: {field_id: field_id}})  }  

Thanks in advance for your answers

how to read a file created in rails using javascript within new.html.erb

Posted: 23 Nov 2016 03:15 AM PST

I have this method in rails where i am creating external events.json file.

 def new          @event=Event.new          @users=User.all          @events=@user.events          tempJson = @events.to_json.html_safe          aFile = File.new("events.json", "r+")          aFile.syswrite(tempJson)      end  

now events.json file is created in my app directory. In my new.html.erb, how to access this file via javascript and set it to a variable?

<script type="text/javascript">            $.getJSON("events.json", function(json) {          debugger;           console.log(json);         });            </script>  

I tried this.. and i get this error message when i inspect,

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3000/users/14/events/events.json  

No comments:

Post a Comment