Monday, October 24, 2016

Rails: rubocop disable Class has too many lines error | Fixed issues

Rails: rubocop disable Class has too many lines error | Fixed issues


Rails: rubocop disable Class has too many lines error

Posted: 24 Oct 2016 08:11 AM PDT

I have a class with constants, many constants. And rubocop is complaining about the length of this Class, which I don't care how long it gets.

I want to disable rubocop's error: "Class has too many lines" but the following is not working:

# rubocop:disable ClassLength  

What is the correct metric that I need to disable?

what is the best way to query?

Posted: 24 Oct 2016 08:15 AM PDT

i am having two models employee and in_outs. the association between these are employee has many in_outs and in_out belongs to employee.i want to display the attendance of all the employees. For this my current logic is this.

def view_all_employee_attendance    employees = Employee.all    @all_employess_punch_in_outs = []    employees.each do |employee|      @all_employess_punch_in_outs << employee.in_outs.where('date >= ? and date <= ?', Date.today.at_beginning_of_month, Date.today)    end  end  

and in view :

      <tbody>          <% @all_employess_punch_in_outs.each do |punch_record| %>            <tr>              <td><%= punch_record.employee.name %></td>              <td><%= punch_record.check_in_req %></td>                 <td><%= punch_record.check_out_req %></td>               </tr>          <% end %>        </tbody>  

in this case in my view again queries are executing. how to make this query optimise in view and in action by using eagerloading?

remember previous input value in ruby

Posted: 24 Oct 2016 08:08 AM PDT

I have this sample class below.

class MyClass    def initialize(options = {})      @input = options[:input]    end      def trigger      # I want to remember previous input value if this method called.      input    end  end  

How can I store or remember the previous value that was previously input? For example.

my_class = MyClass.new(input: "first")  my_class.trigger  => first  

If I call:

my_class.input = "second"  

I want to remember the previous value input which is "fisrt". How can I achieve this?

Rails with Angular 2 ( for stand-alone web apps)?

Posted: 24 Oct 2016 08:12 AM PDT

I have been learning rails for over 4-5 months.I would say i am intermediate(ish) on rails.Past week, i got interested in angular2.Since it is written in TypeScript, it was little diffrent for me.Can rails do what angular2 can do? I mean single page app things? Should i invest the time to learn it, or just move along with rails? And if i leave angular2, can i still make single page rails apps? I know this might not be the place for this question, but i haven't got an answer from quora for past 4 days.This question really bothering me mentally and psyhically. It is bothering my mind, and preventing me to learn anything at all.Please help.

Assets not rendering in production rails

Posted: 24 Oct 2016 08:15 AM PDT

I have precompiled the assets in production but the application is not able to load the assets. My app is deployed on AWS EC2

enter image description here

I checked in the server in public/assets folder the application.css is present. enter image description here but still it says 404 error.

My production.rb configuration is

enter image description here

relationship between students, teacher , periods and attenance

Posted: 24 Oct 2016 08:04 AM PDT

i have User model and UserRole (teacher, student and principle) every class has many students and one teacher only and every student has many classes. every class has many period. how can i set attendance for class as every period has it own attendance for each student and how i create relationship between user and class and period and attendance

Possible to specify backup configuration in yaml file?

Posted: 24 Oct 2016 06:48 AM PDT

I'm using the following gem for authenticating with my LDAP server for user authentication...

https://github.com/cschiewek/devise_ldap_authenticatable

In my configuration file I use the following, but I would like to have it setup so that if the "primary" server is down it would use a secondary server for authenticating.

development:  host: blt01.sub.domain.net  port: 389  attribute: sAMAccountName  base: XXX  admin_user: XXXX  admin_password: XXXX  ssl: false  

So in the above example I would have the primary: blt01.sub.domain.net and would like to specify a secondary: blt02.sub.domain.net somehow. Just not sure how that would be accomplished.

Rails routing all subdomains with wildcard

Posted: 24 Oct 2016 07:21 AM PDT

I have an existing site with the pattern:

CappedIn.com/users/1

I would like my users to also be accessible via

MyUsername.CappedIn.com

I would like to be able to catch all subdomains and then perform a quick lookup in a controller and render a user profile. The rendered URL would be of course MyUsername.CappedIn.com

Is this possible? How can it be achieved?

Note that I am currently on Rails 3.2 but will be migrating to Rails 5. So a Rails 5 solution would be best.

Clean implementation for multiple decisions in ruby

Posted: 24 Oct 2016 07:15 AM PDT

background

I'm writing an API that processes data from an external application. My application processes JSON responses from the external application and offers relevant information to consumers of my service. (These consumers are internal to my organisation)

The external application has an API that allows me to check for updates. Updates are triggered by events. The API offers 12 different types of events. The event types are offered in a string format. (ex. 'MoveEvent', 'DeleteEvent', 'CreateEvent')

I need to write a specific processing algorithm for each event.

Problem

I'm looking for a clean, DRY and SOLID way to implement the event processing system. The focus for this application is on code quality and a solid architecture.

My solution and thoughts

There are a number of ways to tackle this issue, but my best guess so far has been:

  • Create a hash that holds the string name of the event types and map them to a processing class.
  • Use the Strategy pattern to define a common interface for all the processing classes to adhere to, so that any mediating class only needs to know the message to which the processing classes can respond.
  • Use some sort of factory (method) to instantiate a concrete implementation.

I'm explicitly looking to ignore a long if-elsif-else solution, unless someone can convince me to do otherwise.

Suggestions and criticism is always welcome, thanks!

Nginx not serving static content over rails

Posted: 24 Oct 2016 06:50 AM PDT

I want to serve static images with nginx. I have in my nginx.conf

location /i/ {        alias /home/matt/images/;  }  

I am going to server.com/i/928675140291b6.jpg Just to see if it will serve the image, But I'm getting in production.log:

ActionController::RoutingError (No route matches [GET] "/i/928675140291b6.jpg"):

The response to curl -I server.com/i/928675140291b6.jpg:

HTTP/1.1 404 Not Found  Server: nginx/1.10.0 (Ubuntu)  Date: Mon, 24 Oct 2016 13:49:50 GMT  Content-Type: text/html; charset=utf-8  Content-Length: 1564  Connection: keep-alive  X-Request-Id: abb0cb6c-e922-4186-b245-e78b21a88919  X-Runtime: 0.007451  

Rails flash with AJAX request without page refresh

Posted: 24 Oct 2016 06:27 AM PDT

Im hoping there is a cleaning way of getting flash messages to work in an ajax call using React. Been looking on the web and, honestly, Im sure it can be done without much added code.

def my_method   [...]     flash[:success] = "Yea bouy."   if request.xhr?      render :json => {                          :order => true,                      }   end  end  

I'm not doing a page redirect and was wondering how to get a simple flash to show. Anwers around showing adding more methods. Could I have the flash code within my method? Something like:

def my_method   [...]   if request.xhr?      render :json => {                          :order => true,                      }   end   return flash[:success] = "Yea bouy." # Only works when page refreshes.  end  

Why Rails does not add record to table from associations?

Posted: 24 Oct 2016 06:05 AM PDT

I have 2 model classes: Chocolate and Kind:

class Chocolate < ActiveRecord::Base    has_many :kinds    accepts_nested_attributes_for :kinds  

and

class Kind < ActiveRecord::Base    belongs_to :chocolate  

I have the next form:

= simple_form_for @chocolate do |ch|    = simple_fields_for :kinds, @chocolate.kinds.build(kind: 'Bitter') do |k|      = k.input :kind    = ch.input :netto     = ch.submit  

So, when I submit my form, it adds a new record to my chocolates table, but it does not add a record to my kinds table, through associations.

In chocolateController I have:

private  def chocolate_params    params.require(:chocolate).permit(:netto, kinds_attributes: [:kind])  end  

So, why it does not write to my table with associations? Where have I a mistake?

What is the geom and 26918 mean [on hold]

Posted: 24 Oct 2016 05:19 AM PDT

pic

from website

I want to use postgis and ST_Dwithin funtions in rails but I don't understand it

Celluloid deadlock during rails request

Posted: 24 Oct 2016 05:16 AM PDT

I have the following controller path that is supposed to upload a file to azure.

def do_upload(upload, container_name, path, name, data)      Azure.config.storage_account_name = APP_CONFIG['ac_name']      Azure.config.storage_access_key = APP_CONFIG['key']      azure_blob_service = Azure::Blob::BlobService.new        begin        container = azure_blob_service.get_container_properties(container_name)      rescue => error        puts error        upload.upload_failed = true        upload.save        render :body => nil, :status => 503 and return      end        begin        azure_blob_service.create_block_blob(container.name, path + name, data, {chunking: true, timeout: 300})      rescue => error        puts error        upload.upload_failed = true        upload.save        render :body => nil, :status => 503 and return      end        upload.number_of_files += 1 unless (params[:type] == 'thumbnail' || params[:type] == 'model')      upload.save        render json: { :status => 200 } and return    end  

Im using azure-contrib to upload the chunked file to azure and azure-contrib in turn uses Celluloid.

The error I get is:

I, [2016-10-24T11:42:15.290622 #65239]  INFO -- : Completed 500 Internal Server Error in 93ms (ActiveRecord: 4.7ms)  F, [2016-10-24T11:42:15.296640 #65239] FATAL -- :  F, [2016-10-24T11:42:15.312435 #65239] FATAL -- : fatal (No live threads left. Deadlock?):  F, [2016-10-24T11:42:15.312543 #65239] FATAL -- :  

Delete object from s3 bucket Rails 5 aws-sdk

Posted: 24 Oct 2016 05:18 AM PDT

I'm new to RoR.

I've configured my webapp to upload objects to s3 using 'aws-sdk' gem. The connection runs ok and the objects are uploaded correctly.

However, I struggle to delete those objects from Rails. I get this error:

This XML file does not appear to have any style information associated with it. The document tree is shown below.  <Error>  <Code>MethodNotAllowed</Code>  <Message>  The specified method is not allowed against this resource.  </Message>  <Method>POST</Method>  <ResourceType>OBJECT</ResourceType>  

SONGS_CONTROLLER >

class SongsController < ApplicationController      def index      @songs = Song.all    end      def create      #make an object in your bucket for the upload      file_to_upload = params[:file]      file_name = params[:file].original_filename      bucket = S3.bucket(S3_BUCKET.name)        obj = bucket.object(file_name)      #byebug        #upload the file:      obj.put(        acl: "public-read",        body: file_to_upload        )        #create an object for the upload      @song = Song.new(        url: obj.public_url,        name: obj.key        )        #save the upload      if @song.save        redirect_to songs_path, notice: 'File successfully uploaded'      else        flash.now[:notice] = 'There was an error'        render :new      end    end      def delete      @song = Song.find(params[:file])      obj = bucket.object(@song.key)      obj.delete      @song.destroy    end    end  

INDEX.HTML.RB >

  <% @songs.each do |song| %>    <ul>      <%= link_to song.name, song.url %>      ///      <%= link_to 'Delete', song.url + song.name, method: :delete, data: {confirm: 'Do you want to delete this song?'} %>    </ul>    <% end %>  

ROUTES >

Rails.application.routes.draw do    get 'songs/index'    get 'songs/create'    get 'songs/delete'    root 'songs#index'    resources :songs  end  

multi level embeds_many mongoid query

Posted: 24 Oct 2016 04:30 AM PDT

I have 3 classes, A, B, and C.

class A      include Mongoid::Document      embeds_many :bs    class B      include Mongoid::Document      embeds_many :cs      embedded_in :a      field :category, type: String    class C      include Mongoid::Document      embedded_in :b      field :description, type: String  

I want to find all A's such that they have an embedded B with category "cat1" which has an embedded C with description "good" AND that have an embedded B with category "cat2" which has an embedded C with description "great."

I can't seem to come up with a query that doesn't find criss-crossed C's (returns A's with embedded B's that have category "cat1" with description "great."

What I really want logically is something like this:

find all A's that have (an embedded B with category "cat1" and that has an embedded C with description "good") AND (an embedded C with category "cat2" and that has an embedded C with description "great").

By building a compound where query, I can only get a locus with that allows the C's restriction to trigger a hit regardless of whether it's parent B has category "cat1" or "cat2":

A.where(:"bs.category" => "cat1").    where(:"bs.cs.description" => "good").    where(:"bs.category" => "cat2").    where(:"bs.cs.description" => "great")  

This doesn't do what I'm trying to achieve. What I really want is something like this, but the syntax doesn't seem to exist:

A.where((:"bs.category" => "cat1").    where(:"bs.cs.description" => "good")).    where((:"bs.category" => "cat2").    where(:"bs.cs.description" => "great"))  

The only thing I can get to work is to & two different loci with two different queries, but I need to gang together up to 20 selectors and this is going to get inefficient very quickly.

Anyone have any idea how to build this kind of compound query or if it's possible in mongoid?

Thanks for any help, Kevin

Group by bucket (with NULL values)

Posted: 24 Oct 2016 05:17 AM PDT

I have the following tables:

  1. entries (id, title, text, duplicate_bucket_id)
  2. duplicate_buckets (id, comment)

So every entry can be in a duplicate bucket. Now I want to get all entries without the duplicates:

SELECT MIN(id) FROM entries GROUP BY duplicate_bucket_id  

The problem with this query is that it also groups all the entries without a duplicate_bucket_id to only one entry with NULL.

So I need something like this

(SELECT MIN(id) FROM entries WHERE duplicate_bucket_id IS NOT NULL GROUP BY duplicate_bucket_id)  UNION  (SELECT id FROM entries WHERE duplicate_bucket_id IS NULL)  

This query gives me the correct result, but ActiveRecord can't use UNIONs.

Alternatively, I can use this query with a subquery:

SELECT * FROM entries WHERE duplicate_bucket_id IS NULL OR id IN    (SELECT MIN(id) FROM entries WHERE duplicate_bucket_id IS NOT NULL GROUP BY duplicate_bucket_id )  

In this query, I must place additional where-clauses in AND outside of the subquery. So the query gets quite complicated and I don't know yet, how to use the Ransack Gem with such a query...

The query would be simple, if every "entry" would be in a "duplicate_bucket" - buckets of size 1 (I could use *SELECT * FROM entries GROUP BY duplicate_bucket_id*). But I want to avoid to have entries in a duplicate_bucket, if the entry don't have a duplicate. Is there a simple query (no unions, no subqueries) to get all entries without their duplicates?

Dataset

entries(id, title, text, duplicate_bucket_id)

1, 'My title', 'Bla bla', 1  2, 'Hello', 'Jaha', 1  3, 'Test', 'Bla bla', 1  4, 'Foo', 'Bla', NULL  5, 'Bar1', '', 2  6, 'Bar2', '', 2  

duplicate_buckets (id, comment)

1, 'This bucket has 3 entries'  2, 'Bar1 and Bar2 are duplicates!'  

Result

1, 'My title', 'Bla bla', 1  4, 'Foo', 'Bla', NULL  5, 'Bar1', '', 2  

Update of latitude and longitude does not work in active admin

Posted: 24 Oct 2016 05:06 AM PDT

I am building an app for renting rooms. I am using active admin and the geocoder gem. Now to my issue: I want to update the address of a room in the active admin panel which works perfectly but it will not update the longitude and latitude columns autoamtically for me... and I have no idea why? How can I make this work?

I have permited the params in (room.rb - activeadmin)

permit_params :longitude, :latitude  

I am using also an after_validation in (room.rb - model)

geocoded_by :address  after_validation :geocode, if: :address_changed?  

how to get text_filed value in a variable before submit form in rails

Posted: 24 Oct 2016 04:12 AM PDT

I am new in ruby on rails, Here i want to get text_field value in a variable and pass this value to edit method.

I am using java script model but can not understand how to get value and pass.

_employee_details.html.erb

     <div class="edit-recr-wrp1">                    <button type="button" class="btn btn-primary fa fa-pencil-square-o" data-toggle="modal" data-target="#exampleModal1" data-whatever="<%= emp['offer_letter_id'] %>"></button>               </div>        <div class="modal fade" id="exampleModal1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">    <div class="modal-dialog" role="document">      <div class="modal-content">        <div class="modal-header">          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>        </div>        <div class="modal-body">          <h2 class="text-center">Edit <span>Employee Details</span></h2>          <div class="post-new-job head-border">            <div class="alert alert-success" role="alert" id='success-job' style='display:none;'>Employee Details is successfully added.</div>              <div class="form-body">                     <div class="mydata1">                      <%= text_field :ol_id, { class: 'form-control', id: 'recipient-name' } %>                  </div>                    <%= form_for :employee_details, url: hr_path(:ol_id), method: :patch  do |f| %>                                   <div class="col-md-12">                         <div class="mydata">                         <%= f.hidden_field :offer_letter_id, { class: 'form-control', id: 'recipient-name' } %>                       </div>                         <div class="form-group">                          <label class="control-label">Employee ID</label>                          <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-user"></i> </span>                            <%= f.text_field :employee_id, { :required => true, placeholder: 'E12345678', class: 'form-control' } %>                          </div>                        </div>                          <div class="form-group">                          <label class="control-label">Bank Account</label>                          <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-university"></i> </span>                            <%= f.text_field :bank_ac, { :required => true, placeholder: '06464060852634865', class: 'form-control' } %>                          </div>                        </div>                          <div class="form-group">                          <label class="control-label">Bank IFSC Code</label>                          <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-code"></i> </span>                            <%= f.text_field :bank_ifsc, { :required => true,  placeholder: 'SBI012356', class: 'form-control' } %>                          </div>                        </div>                         <div class="form-group">                          <label class="control-label">End of Date</label>                          <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-calendar"></i> </span>                            <%= f.text_field :work_end_date, {  placeholder: 'MM/DD/YYYY', id: 'datepicker1', class:"datepicker_style" } %>                          </div>                        </div>                          <div class="form-group">                          <label class="control-label">Gender</label>                          <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-male fa-female"></i> </span>                            <%= f.select :gender, ['Male', 'Female'], { :required => true }, class: "form-control" %>                          </div>                         </div>                          <div class="form-group">                          <label class="control-label">Spouse Name</label>                          <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-user"></i> </span>                            <%= f.text_field :spouse_name, { :required => true, placeholder: 'Father/Mother/Wife name', class: "form-control" } %>                          </div>                        </div> <br>                          <div class="form-group">                          <a><%= f.submit "Edit Employee Details", :class => "btn btn-primary" %></a>                         </div>                      </div>                      <div class="col-md-2"></div>                                  <%- end -%>              </div>                </div>         </div>      </div>    </div>  </div>        <script type="text/javascript">      $('#exampleModal1').on('show.bs.modal', function (event) {        var button = $(event.relatedTarget)        var recipient = button.data('whatever')        var modal = $(this)        modal.find('.mydata1 input').val(recipient)      });  </script>  

the problems is here take ol_id and pass to hr_path

 <div class="mydata1">                  <%= text_field :ol_id, { class: 'form-control', id: 'recipient-name' } %>              </div>                <%= form_for :employee_details, url: hr_path(:ol_id), method: :patch  do |f| %>   

Can't cast ReportImage to string in carrierwave Rails4

Posted: 24 Oct 2016 04:11 AM PDT

Following ocumentation of carrierwave I added gem, generated ReportImage uploader, added

t.string :report_image, null: true, unique: true  

to Report migration table and

mount_uploader :report_image, ReportImage  

to Report model.

But I get TypeError: can't cast ReportImage to string when trying to create Report without ReportImage (nil)

Someone know how to fix it?

Retreive Values from Relationship table of has_and_belongs_to_many on Rails5

Posted: 24 Oct 2016 04:33 AM PDT

I have two tables Role and User, and I linked those two tables with has_and_belongs_to_many relationship with rails.

I'm successfully insert the data into the third table which is created by has_and_belongs_to_many relationship. Using the following code

def create  user_params[:password] = User.hash(user_params[:password])  @user = User.new(:first_name => user_params[:first_name],                   :last_name=>user_params[:last_name],                   :email => user_params[:email],                   :contact_number=>user_params[:contact_number],                   :password=>user_params[:password])    @roles = user_params[:roles];  for role in @roles    @user.roles << Role.find(role)  end  if @user.save    respond_to do |format|      msg = { :status => "ok", :message => "User Creation Success!" }      format.json  { render :json => msg }    end  end  end  

Now my problem is how do I read the valuse from the relationship table and how do I update any value to the relationship table.

Rails migration and CREATE UNIQUE INDEX not working on DashDB / DB2

Posted: 24 Oct 2016 07:49 AM PDT

I'm working on Rails 4.2.7 application on IBM Bluemix using Ruby 2.3.0. When I've installed Devise User model migration has been generated, just a standard file, no fancy options. During the deploy the migration is firing up three queries. First one for users table creation:

CREATE TABLE users (   id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1) PRIMARY KEY,    email varchar(255) DEFAULT '' NOT NULL,    encrypted_password varchar(255) DEFAULT '' NOT NULL,    reset_password_token varchar(255),     reset_password_sent_at timestamp,     remember_created_at timestamp,     sign_in_count integer DEFAULT 0 NOT NULL,     current_sign_in_at timestamp,     last_sign_in_at timestamp,     current_sign_in_ip varchar(255),     last_sign_in_ip varchar(255),     created_at timestamp NOT NULL,     updated_at timestamp NOT NULL)  

And two for unique index creation:

CREATE UNIQUE INDEX index_users_on_email ON USERS(email)  CREATE UNIQUE INDEX index_users_on_reset_password_token ON USERS(reset_password_token)  

First statement runs fine, the table is being created. However, the problem is that the table type is created with organize by column by default. CREATE UNIQUE INDEX statements were failing and it has appeared that to run them, the table has to be organized by row.

I can remove the migration and create the table directly in the DB via SQL statement and adding organize by row clause at the end and then run two remaining queries.

The problem is that I've encountered the same issue when migration wanted to run two below queries it did fail again:

CREATE TABLE schema_migrations (version varchar(255) NOT NULL)  CREATE UNIQUE INDEX unique_schema_migrations ON schema_migrations (version)  

I think I can keep bumping on the same problem again and so I would like to find a way to make all tables organized by row by default, preferably with the migration. Has anyone encountered this issue before?

My manifest.yml looks following:

applications:  - path: .    buildpack: https://github.com/cloudfoundry/ruby-buildpack.git    memory: 1024M    instances: 1    domain: eu-gb.mybluemix.net    name: windykacja    host: windykacja    disk_quota: 1024M    services:    - dashDB-win  

and here is my gemfile:

source 'https://rubygems.org'  ruby '2.3.0'    gem 'rails', '4.2.7'  gem 'sass-rails', '~> 5.0'  gem 'uglifier', '>= 1.3.0'  gem 'coffee-rails', '~> 4.1.0'  gem 'devise'  gem 'bootstrap-sass', '~> 3.3.6'  gem 'jquery-rails'  gem 'turbolinks'  gem 'jbuilder', '~> 2.0'  gem 'sdoc', '~> 0.4.0', group: :doc      group :production do      gem 'rails_12factor'      gem 'ibm_db'  end    group :development, :test do    gem 'byebug'  end    group :development do    gem 'web-console', '~> 2.0'    gem 'spring'    gem 'sqlite3'  end  

Trying to get value of current_user saved in a hidden field

Posted: 24 Oct 2016 03:37 AM PDT

I have a simple rails app in which, in one of the forms, I am trying to save the value of current user into a field using hidden field tag.

My application controller has user_authenticate method which is also setting value of @current_user as below.


ApplicationController

class ApplicationController < ActionController::Base    protect_from_forgery with: :exception    protected     def authenticate_user    if session[:user_id]       # set current user object to @current_user object variable      @current_user = User.find session[:user_id]       return true     else      redirect_to(:controller => 'sessions', :action => 'login')      return false    end  end  def save_login_state    if session[:user_id]      redirect_to(:controller => 'sessions', :action => 'home')      return false    else      return true    end  end    end  

The receipt model is defined with belongs_to user as below.

Receipt model

class Receipt < ApplicationRecord    belongs_to :currency    belongs_to :user  end  

and the view for form has a hidden field tag as below.

Form

<%= form_for(receipt) do |f| %>      <% if receipt.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(receipt.errors.count, "error") %> prohibited this receipt from being saved:</h2>          <ul>        <% receipt.errors.full_messages.each do |message| %>          <li><%= message %></li>        <% end %>        </ul>      </div>    <% end %>  <div align="center" style="text-align: right; width: 50%">    <div class="field">      <%= f.label :receipt_date %>      <%= f.date_select :receipt_date %>    </div>  </br>    <div class="field">      <%= f.label :receipt_amount %>      <%= f.text_field :receipt_amount %>    </div>  </br>    <div class="field">      <%= f.label :Currency%>      <%= f.collection_select :currency_id, Currency.all, :id, :currency %>    </div>  </br>    <div class="field">      <%= f.hidden_field :user_id, :user_id => @current_user %>    </div>    </br>   <div class="actions">      <%= f.submit %>    </div>  </div>    <% end %>  

Yet when I save the record I get an error - "User must exist". So essentially, the user field is going as 'nil'.

My receipt controller is like this


ReceiptsController

class ReceiptsController < ApplicationController      before_action :set_receipt, only: [:show, :edit, :update, :destroy]      # GET /receipts    # GET /receipts.json    def index      @receipts = Receipt.all    end      # GET /receipts/1    # GET /receipts/1.json    def show    end      # GET /receipts/new    def new      @receipt = Receipt.new    end      # GET /receipts/1/edit    def edit    end      # POST /receipts    # POST /receipts.json    def create      @receipt = Receipt.new(receipt_params)        respond_to do |format|        if @receipt.save          format.html { redirect_to @receipt, notice: 'Receipt was successfully created.' }          format.json { render :show, status: :created, location: @receipt }        else          format.html { render :new }          format.json { render json: @receipt.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /receipts/1    # PATCH/PUT /receipts/1.json    def update      respond_to do |format|        if @receipt.update(receipt_params)          format.html { redirect_to @receipt, notice: 'Receipt was successfully updated.' }          format.json { render :show, status: :ok, location: @receipt }        else          format.html { render :edit }          format.json { render json: @receipt.errors, status: :unprocessable_entity }        end      end    end      # DELETE /receipts/1    # DELETE /receipts/1.json    def destroy      @receipt.destroy      respond_to do |format|        format.html { redirect_to receipts_url, notice: 'Receipt was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_receipt        @receipt = Receipt.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def receipt_params        params.require(:receipt).permit(:receipt_date, :receipt_amount, :currency_id, :user_id)      end  end  

When authenticated using API, Devise redirects to its default login view page every second time on failure

Posted: 24 Oct 2016 02:41 AM PDT

I am using token based authentication system for my APIs which is built based on Devise. The user is authorised to access the pages only when the email and mobile number linked with his/her account has been verified. If anyone of the above is not verified, the user gets the 403 access forbidden error message.

def authenticate_user!      unless current_user        authorization_failed_error      end      if current_user.confirmed_at.blank?        unconfirmed_email_error      elsif current_user.mobile_confirmed_at.blank?        unconfirmed_mobile_error      end  end  

When an user with a unconfirmed email is trying to access a content through the API, error message is thrown. But if the same user tries for the second time, Devise redirects the user to the login view page.

Above scenarios occur alternatively every time.

current_user is set by the set_user_by_token function of the Devise, as below.

def set_user_by_token(mappings=nil)      rc = resource_class(:user)      # no default user defined      return unless rc        #gets the headers names, which was set in the initialize file      uid_name = 'Uid'      access_token_name = 'Access-Token'      client_name = 'Client'      expiry_name = 'Expiry'        # parse header for values necessary for authentication      uid        = request.headers[uid_name] || params[uid_name]      @token     ||= request.headers[access_token_name] || params[access_token_name]      @client_id ||= request.headers[client_name] || params[client_name]        # client_id isn't required, set to 'default' if absent      @client_id ||= 'default'        # check for an existing user, authenticated via warden/devise, if enabled      devise_warden_user = warden.user(rc.to_s.underscore.to_sym)      if devise_warden_user && devise_warden_user.tokens[@client_id].nil?        @used_auth_by_token = false        @resource = devise_warden_user        @resource.create_new_auth_token      end        # user has already been found and authenticated      return @resource if @resource and @resource.class == rc        # ensure we clear the client_id      if !@token        @client_id = nil        return      end        return false unless @token        # mitigate timing attacks by finding by uid instead of auth token      user = uid && rc.find_by_email(uid)        if user && user.valid_token?(@token, @client_id)        # sign_in with bypass: true will be deprecated in the next version of Devise        if self.respond_to? :bypass_sign_in          bypass_sign_in(user, scope: :user)        else          sign_in(:user, user, store: false, bypass: true)        end        @resource = user        return @resource      else        # zero all values previously set values        @client_id = nil        return @resource = nil      end   end  

I am not sure why Devise(or Warden) behaves like this every second time. It would be of great help if someone could figure this out.

Rails, Capistrano, Nginx, Unicorn - Application has been already initialized

Posted: 24 Oct 2016 02:24 AM PDT

I followed ChuckJHardy example on how to deploy a rails app to a VPS using Capistrano, Nginx, Unicorn. The deployment process passed from my local machine but my rails application is not loading fine. I am getting the following errors enter image description here

I checked the log from my unicorn.rb log and I see the bellow errors.

Please help me with some Idea's I am totally confuse.

I, [2016-10-23T19:40:36.183042 #7200]  INFO -- : Refreshing Gem list  E, [2016-10-23T19:40:36.197960 #7200] ERROR -- : error reloading config_file=/home/deploy/apps/onozor/current/config/unicorn/production.rb: Application has been already initialized. (RuntimeError)  E, [2016-10-23T19:40:36.198056 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/gems/railties-4.0.6/lib/rails/application.rb:214:in `initialize!'  E, [2016-10-23T19:40:36.198095 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/gems/railties-4.0.6/lib/rails/railtie/configurable.rb:30:in `method_missing'  E, [2016-10-23T19:40:36.198142 #7200] ERROR -- : /home/deploy/apps/onozor/releases/20161023193809/config/environment.rb:5:in `<top (required)>'  E, [2016-10-23T19:40:36.198165 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/gems/activesupport-4.0.6/lib/active_support/dependencies.rb:229:in `require'  E, [2016-10-23T19:40:36.198199 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/gems/activesupport-4.0.6/lib/active_support/dependencies.rb:229:in `block in require'  E, [2016-10-23T19:40:36.198233 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/gems/activesupport-4.0.6/lib/active_support/dependencies.rb:214:in `load_dependency'  E, [2016-10-23T19:40:36.198260 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/gems/activesupport-4.0.6/lib/active_support/dependencies.rb:229:in `require'  E, [2016-10-23T19:40:36.198295 #7200] ERROR -- : config.ru:4:in `block in <main>'  E, [2016-10-23T19:40:36.198315 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/gems/rack-1.5.5/lib/rack/builder.rb:55:in `instance_eval'  E, [2016-10-23T19:40:36.198340 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/gems/rack-1.5.5/lib/rack/builder.rb:55:in `initialize'  E, [2016-10-23T19:40:36.198373 #7200] ERROR -- : config.ru:1:in `new'  E, [2016-10-23T19:40:36.198393 #7200] ERROR -- : config.ru:1:in `<main>'  E, [2016-10-23T19:40:36.198444 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/gems/unicorn-5.1.0/lib/unicorn.rb:56:in `eval'  E, [2016-10-23T19:40:36.198496 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/gems/unicorn-5.1.0/lib/unicorn.rb:56:in `block in builder'  E, [2016-10-23T19:40:36.198518 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:752:in `build_app!'  E, [2016-10-23T19:40:36.198552 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:733:in `load_config!'  E, [2016-10-23T19:40:36.198590 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:314:in `join'  E, [2016-10-23T19:40:36.198616 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/gems/unicorn-5.1.0/bin/unicorn:126:in `<top (required)>'  E, [2016-10-23T19:40:36.198648 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/bin/unicorn:23:in `load'  E, [2016-10-23T19:40:36.198669 #7200] ERROR -- : /home/deploy/apps/onozor/shared/bundle/ruby/2.3.0/bin/unicorn:23:in `<top (required)>'  E, [2016-10-23T19:40:36.198686 #7200] ERROR -- : /home/deploy/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/cli/exec.rb:74:in `load'  E, [2016-10-23T19:40:36.198738 #7200] ERROR -- : /home/deploy/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/cli/exec.rb:74:in `kernel_load'  E, [2016-10-23T19:40:36.198762 #7200] ERROR -- : /home/deploy/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/cli/exec.rb:27:in `run'  E, [2016-10-23T19:40:36.198806 #7200] ERROR -- : /home/deploy/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/cli.rb:332:in `exec'  E, [2016-10-23T19:40:36.198862 #7200] ERROR -- : /home/deploy/.rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run'  

Chartkick for Newsletters

Posted: 24 Oct 2016 03:27 AM PDT

Is it possible to use Chartkick without rails? I would like to write a ruby script that generates a HTML newsletter which can be send by mail. The output should be a HTML file.

How do I integrate Chartkick into my project and supply it with the data needed?

Unable to connect to Facebook via Koala on Rails 5

Posted: 24 Oct 2016 01:40 AM PDT

My final aim is to create a cron job that retrieves my Facebook feed every day.

I've been trying to connect to my Facebook app using Rails (5.0.0.1) and Koala gem (2.4.0) on a single controller so the server authenticates himself and get the token to access the Graph API.

The problem is that the Koala method get_user_info_from_cookie returns nil therefore I don't know how to get the infamous Access Token. Is there anything wrong?

Here what is in my controller.

before_action :parse_facebook_cookies    def parse_facebook_cookies      @oauth = Koala::Facebook::OAuth.new( ENV['FB_APP_ID'], ENV['FB_SECRET_KEY'] )      @facebook_cookies ||= @oauth.get_user_info_from_cookie(cookies)  end  

My environment variables ENV['FB_APP_ID'] and ENV['FB_SECRET_KEY'] work and cookies is not empty, I've already checked.

Rails: how to render nested form in table

Posted: 24 Oct 2016 01:57 AM PDT

For example, I have two models:

class Task < ApplicationRecord     has_many :task_details  end    class TaskDetail < ApplicationRecord    belong_to :task  end  

I want to display a table, each row in table is one TaskDetail and allow user input. After that user submits, all data will put to server. Here is my code: (Note that: I @data[:task] is a task object because I want to return a hash with some information for view)

<%= form_for @data[:task], :url => tasks_path do |f| %>      <table> ... </table>  <% end %>  

My question is: How can I do as my requirement.

thanks

After deploying I need to refresh server for changes to reflect

Posted: 24 Oct 2016 01:30 AM PDT

I'm deploying a rails app using a service which uses a symblink method with current/release folders on Ubuntu 14.04. However every time I deploy I have to refresh the server in order to see changes reflected by running:

sudo nginx -s reload  

If I do a standard FTP deploy without any symblinks I can see the changes immediately. Is there anyway around refreshing the server in order in order for the updates to reflect?

Thanks

Why does Google API set +01 offset no matter input?

Posted: 24 Oct 2016 01:21 AM PDT

I'm using Google's API Explorer for their Calendar API on this page.

I am inserting an event { "end": { "dateTime": "2016-10-31T06:30:00Z" }, "start": { "dateTime": "2016-10-31T06:00:00Z" } } and have tried the following datetime formats:

2016-10-31T06:00:00Z  2016-10-31T06:00:00-00:00  2016-10-31T06:00:00+00:00  

But no matter input format, Google chooses to add an hour when setting the datetime. The response is always:

"start": {   "dateTime": "2016-10-31T07:00:00+01:00"  }  

I'm currently in Stockholm, which has +2 hours offset. I've tried both setting the separate time_zone field and omitting the separate time_zone field.

Why is this happening? And, is there any "right way" or do I simply need to take this added hour into account when setting time?

1 comment:

  1. Rails: Rubocop Disable Class Has Too Many Lines Error >>>>> Download Now

    >>>>> Download Full

    Rails: Rubocop Disable Class Has Too Many Lines Error >>>>> Download LINK

    >>>>> Download Now

    Rails: Rubocop Disable Class Has Too Many Lines Error >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete