vendredi 30 juin 2017

Why my rails command works differently with system() than in terminal?

The command that I'm trying to run is rails _3.2.13_ new App

When I run it in command line it creates a Rails app with version 3.2.13, but when I run it with system "rails _3.2.13_ new #{self.name} -T -B" it creates a Rails app with the latest version of Rails not 3.2.13 version.

Ruby on Rails undefined method 'due_date' #

I'm just new in RoR and I encountered this problem. I am making a system, basically a system that manages dorm transactions. so i have a users_controller, accountabilities_controller (for dormer's accountabilities), and violations controller. i have this snippet in my index.html.erb for my users:

                <% @users.each do |user| %>
                    <% if !(user.admin?) && !user.archived? %>
                        <tr>
                            <td><%= user.id %></td>
                            <td><%= link_to "#{user.first_name}, #{user.last_name} #{user.mi}", url_for(user) + '/personal-info' %></td>
                            <td><%= user.student_no %></td>
                            <td><%= user.email %></td>
                            <td><%= user.sts_bracket %></td>
                            <td>
                                <% if user.activated? %>
                                    Activated
                                <% else %>
                                    Not Activated
                                <% end %>
                            </td>
                            <td>
                                <%= link_to "Edit", (user.activated ? edit_ddms_user_path(user) : '#'), class: 'btn btn-primary' %>
                                <%= link_to "Archive", change_ddms_user_path(user), data: {confirm: "Are you sure?"}, class: 'btn btn-primary'%> 
                                <%= link_to "Add accountability", ddms_accountabilities_new_path(:user_id => user.id), class: 'btn btn-primary' %>
                                <%= link_to "Add violation", ddms_violations_new_path(:user_id => user.id), class: 'btn btn-primary' %>
                            </td>
                        </tr>
                    <% end %>
                <% end %>

as you can see, i have a link/button for adding violations and accountabilities. when i add accountability, i don't encounter a problem. but when i try to add violation, everytime i submit the form, i get this nomethoderror:

nemethoderror: undefined method 'due_date' for ddms_violation..

I've searched other problems like this before and usually get it to work. the problem is usually found in the defined params. but one thing that is bothering me in this situation is that the 'due_date' attribute is not in my violation_params:

 def violation_params
      params.require(:ddms_violation).permit(:title, :remarks, :user_id)
 end

because 'due_date' is not an attribute even in my violations table:

class CreateDdmsViolations < ActiveRecord::Migration[5.0]
  def change
    create_table :ddms_violations do |t|
      t.string :title
      t.text :remarks
      t.boolean :resolved, default: false
      t.integer :user_id

      t.timestamps
    end
  end
end

and this 'due_date' is an attribute in my accountability table:

def change
    create_table :ddms_accountabilities do |t|
      t.string :accountability
      t.text :remarks
      t.boolean :resolved, default: false
      t.datetime :due_date

      t.timestamps
    end
end

I am not having any problems with my accountabilities index. so why is it that due_date is still recognized as a part of params in violations? I have read that everytime I render to 'new' I am given a new set of params. I also read that it is a big NO to manually manipulate values in params.

p.s In the calling of 'new' in violations an accountabilities controllers, i am passing a user_id parameters since i am not using table associations. this way i am passing a user_id in a hidden_field in the form. anyway, I am not sure if this is a probable cause of the problem I mentioned above.

Responses will be pretty much appreciated! Thank you!!

User rails console to login as a specific user

I'm using the rails console to and app.get to try to track down a bug that only happens for a specific user. Is there a way to issue a request as that user with apt.get?

Also, I don't have the user's password.

app.get '/account/billing'

Returns a 302 that is redirecting me to the login page. I do have a cookie from an actual request, so one idea I had was to try to stick that in the header so the request would look like it came from that user.

I'm using Rails 3.2.0 for this.

Cassandra Rails not able to do more then one column filter

Rails Cassandra not work with filter more then one column.

my modal

class Template 
  include Cequel::Record
  key :id,:int,index:true
  column :u_id,:uuid,:auto=>true
  column :user_id, :int,index:true
  column :code_type,:text,index:true
  column :name, :text
  column :code_text, :text
  timestamps
end
Template.where(:code_type=>"job_html_template",:user_id=>1).allow_filtering!

Cequel::Record::IllegalQuery: Can't scope by more than one indexed column in the same query

I am using  cequel (3.0.0) 

Can some one please help me what's wrong with this ?

error when comparing dates in sidekiq-cron

When run sidekiq, in log receive this error:

ERROR: CRON JOB: comparison of Time with EtOrbi::EoTime failed
ERROR: CRON JOB: /home/user/.rvm/gems/ruby-2.0.0-p247@script-admin/gems/sidekiq-cron-0.3.1/lib/sidekiq/cron/job.rb:434:in `<'

error in this place

def not_enqueued_after?(time)
  @last_enqueue_time.nil? || @last_enqueue_time < last_time(time)
end

sidekiq running, but logs out this error. and cron workers not started.

maybe it's because I compare the object EtOrbi::EoTime with ruby's standard DateTime object

Tell me how to fix? thanks

jeudi 29 juin 2017

Rails: Call a method from a model in Rails Migration

Trying to call a method from scenario.rb which contains a method called complete_scenario? which returns a boolean inside the migration file but an error states that complete_scenario? is an undefined_method.

class AddCompleteFlagToScenarios < ActiveRecord::Migration

def up
change_table :scenarios do |s|
  s.boolean :complete, s.complete_scenario? :default => false, :null =>false
end

end

def down
  remove_column :scenarios, :complete
end

end

Is there something that I'm doing wrong or forgetting to include? Ultimately, I want to add a new column to Scenario called complete that takes the boolean from Scenario and puts it into the updated table. Thanks.

class Scenario < ActiveRecord::Base
validates :name,
presence: true,
uniqueness: { :case_sensitive => false },
length: { in: 4..60 }

has_many :nodes
has_many :showings, -> { visible }
has_many :courses, :through => :showings

attr_accessor :warnings

amoeba do
enable
include_association [:nodes]
end

...

def complete_scenario?
   (self.unlabeled_choices.empty?) && (self.no_goal_nodes?) && (self.regular_leaf_nodes.empty?) && (self.unconnected_nodes.empty?)
end

How after manipulations with two strings get a string in result as well

Write a method, #present_pet, that takes two arguments: a pet name and an animal type, both strings. It should return a string that announces the pet (e.g. if given "Todd" and "turtle", it should return "Todd the turtle has arrived.").

def present_pet(pet_name, animal)
  pet_name.each_line do |pet_name|
    animal.each_line do |animal|
      puts pet_name[pet_name] + " " + "the" + " " \
           + animal[animal] + " " + "has arrived."
    end
  end
end

and after I run it, I get just the sentence not converted to a string! how would I make it a string ?

Sort users based on their maximum number of followers in Rails

I have 2 tables one is for users(events in my case) and follows which is a join table to users and events, I want to sort my events based on maximum no of followers they have like i can get no of followers of a particular event using

@event.followers.count

but how can I execute a query to get an event with maximum no of followers

something like this =>

@mainevent = Event.includes(:follow).where(start: Time.now-1.days .. Time.now+1.days).order(' *followers_count* ').first

or

@mainevent = Event.find_by_sql( 'followers max using sql query' )

anything to give me event ordered by max no of followers

Putting logic into a Ruby on Rails application: calculate a value for a field when creating a new row of the database

I'm fairly new to Ruby on Rails. I'm building a web app that will ask a patient a series of questions, then calculate a risk using a previously validated model. When a new patient record is created, I want the application to take the data the user entered into the other fields, and use it to calculate the value of the last field. I have the logic written out, but just don't know where to actually code it into my application.

Should it go in the model, view or controller? And how should I go about including it?

My git repo: http://ift.tt/2tnoc6o

This is my view patients/form.html.erb

<%= form_with(model: patient, local: true) do |form| %>
  <% if patient.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(patient.errors.count, "error") %> prohibited this patient from being saved:</h2>

      <ul>
      <% patient.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="form-group">
    <%= form.label :"First Name" %><br>
    <%= form.text_field :firstName, class: "form-control", id: :patient_firstName %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Surname" %><br>
    <%= form.text_field :surName, class: "form-control", id: :patient_surName %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Date of Birth" %>&nbsp &nbsp 
    <%= form.date_select :dob, :start_year=>1900,:end_year=>2030, id: :patient_dob %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Gender" %>&nbsp &nbsp 
    <%= form.select :gender, ["","male", "female"], id: :patient_gender %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Which hospital are you having the opperation in?" %>&nbsp &nbsp 
    <%= form.select :hospital, ["","Beaumont", "Connelly", "St. Josephs", "Naas", "Limerick"], id: :patient_hospital %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"What date are you having the opperation on?" %>&nbsp &nbsp 
    <%= form.date_select :opDate, :start_year=>2017,:end_year=>2027, id: :patient_opDate %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"How would you rate your overall health" %><br>
    <%= form.select :q1, ["","No abnormalities", "Better than expected", "Worse  than expected", "Dementia", "Sick", "Moribund"], id: :patient_q1 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"How is your physical condition in general?" %><br>
    <%= form.select :q2, ["","I can do everything I want", "Slightly impaired, but I feel no impairments in daily activities", "Impaired, I can only take care of domestic chores", "I am completely dependent on help from others"],  id: :patient_q2 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Do you have a heart condition that impedes your physical efforts (as a result of tiredness, pain or shortness of breath)?" %><br>
    <%= form.select :q3, ["","No", "Yes, only during heavy labour", "Yes, during climbing the stairs, in the wind, stress", "Yes, daily, not at rest", "Yes, at rest and increased during any activity"], id: :patient_q3 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Have you ever experienced any feeling of pain or tightness in the chest?" %><br>
    <%= form.select :q4, ["","No", "Yes, only during heavy labour", "Yes, during climbing the stairs, in the wind, stress", "Yes, daily, not at rest", "Yes, at rest and increased during any activity"], id: :patient_q4 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Have you ever had a heart attack?" %><br>
    <%= form.select :q5, ["","No", "Yes, > 12 months ago", "Yes, > 6 and < 12 months ago", "Yes, > 3 and < 6 months ago", "Yes, < 3 months ago"], id: :patient_q5 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Have you ever had a cardiac arrest?" %><br>
    <%= form.select :q6, ["","No", "Yes, > 12 months ago", "Yes, > 6 and < 12 months ago", "Yes, > 3 and < 6 months ago", "Yes, < 3 months ago"], id: :patient_q6 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Have you ever undergone any cardiac surgery or heart catheterization?" %><br>
    <%= form.select :q7, ["","No", "Yes, > 6 months ago", "Yes, > 3 and < 6 months ago", "Yes, > 6 weeks and < 3 months ago", "Yes, < 6 weeks ago"], id: :patient_q7 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Do you ever get palpitations?" %><br>
    <%= form.select :q8, ["","No", "Yes, I have no treatment", "Yes, I am treated with medication"], id: :patient_q8 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Have you been told you have a heart murmur?" %><br>
    <%= form.select :q9, ["","No", "Yes, but no operation", "Yes, I have had an operation"], id: :patient_q9 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Do you have high blood pressure?" %><br>
    <%= form.select :q10, ["","No", "I don't know", "Yes"], id: :patient_q10 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Do you have high cholesterol?" %><br>
    <%= form.select :q11, ["","No", "Yes"], id: :patient_q11 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Do you receive treatment for diabetes (high blood sugar level)?" %><br>
    <%= form.select :q12, ["","No", "Yes, treatment with diet", "Yes, treatment with oral medication", "Yes, treatment with insulin"], id: :patient_q12 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Have you ever had a stroke?" %><br>
    <%= form.select :q13, ["","No", "Yes, but complete recovery", "Yes, with physical impairment/ disability", "Yes, < 2 months ago"], id: :patient_q13 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Do you receive treatment for asthma?" %><br>
    <%= form.select :q14, ["","No", "Yes, sometimes", "Yes, often", "Yes, daily", "Yes, daily and increased over the last six months"], id: :patient_q14 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Do you receive treatment for pulmonary emphysema, chronic obstructive pulmonary disease (COPD) or chronic bronchitis?" %><br>
    <%= form.select :q15, ["","No", "Yes, only during heavy labour", "Yes, always during climbing the stairs, in the wind, stress", "Yes, always even at rest, I need oxygen therapy"], id: :patient_q15 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Do you have Sleep Apnoea?" %><br>
    <%= form.select :q16, ["","No", "Yes"], id: :patient_q16 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Do you have any renal problems or kidney impairment?" %><br>
    <%= form.select :q17, ["","No", "Yes, but with complete recovery", "Yes, treatment with fluid restriction only", "Yes, treatment with dialysis", "Yes, other serious kidney condition (e.g. kidney resection)"], id: :patient_q17 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Have you ever had jaundice or any liver problems?" %><br>
    <%= form.select :q18, ["","No", "Yes, but with complete recovery", "Yes, liver cirrhosis has been diagnosed", "Yes, other serious liver condition (e.g. partial resection)"], id: :patient_q18 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Have you ever unintentionally lost more than 10 kg in a short period of time?" %><br>
    <%= form.select :q19, ["","No", "Yes", "Yes, more than 25% of previous bodyweight"], id: :patient_q19 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Do you smoke?" %><br>
    <%= form.select :q20, ["","No", "Yes"], id: :patient_q20 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Do you consume alcohol?" %><br>
    <%= form.select :q21, ["","No", "Yes, < 3 Units/day", "Yes, > 3 and < 6 Units/day", "Yes, > 6 Units/day"], id: :patient_q21 %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.label :"Do you ever take illicit drugs (Cocaine, Heroin, Ecstasy)?" %><br>
    <%= form.select :q22, ["","No", "No, not anymore", "Yes, every once in a while", "Yes, more the once a week"], id: :patient_q22 %>
  </div>
  <hr>





  <div class="form-group">
    <%= form.label :"ASA grade" %><br>
    <%= form.select :asa, ["","1", "2", "3", "4", "5"], id: :patient_asa %>
  </div>
  <hr>

  <div class="form-group">
    <%= form.submit "Submit for Assessment", class: "btn btn-primary" %>
  </div>
<% end %>

And this is my patient controller

class PatientsController < ApplicationController
  before_action :set_patient, only: [:show, :edit, :update, :destroy]

  # GET /patients
  # GET /patients.json
  def index
    @patients = Patient.all
  end

  # GET /patients/1
  # GET /patients/1.json
  def show
    
  end

  # GET /patients/new
  def new
    @patient = Patient.new
  end

  # GET /patients/1/edit
  def edit
  end

  # POST /patients
  # POST /patients.json
  def create
    @patient = Patient.new(patient_params)
    respond_to do |format|
      if @patient.save
        format.html { redirect_to @patient }
        format.json { render :show, status: :created, location: @patient }
      else
        format.html { render :new }
        format.json { render json: @patient.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /patients/1
  # PATCH/PUT /patients/1.json
  def update
    respond_to do |format|
      if @patient.update(patient_params)
        format.html { redirect_to @patient, notice: 'Patient was successfully updated.' }
        format.json { render :show, status: :ok, location: @patient }
      else
        format.html { render :edit }
        format.json { render json: @patient.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /patients/1
  # DELETE /patients/1.json
  def destroy
    @patient.destroy
    respond_to do |format|
      format.html { redirect_to patients_url, notice: 'Patient was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_patient
      @patient = Patient.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def patient_params
      params.require(:patient).permit(:firstName, :surName, :dob, :gender, :hospital, :opDate, :q1, :q2, :q3, :q4, :q5, :q6, :q7, :q8, :q9, :q10, :q11, :q12, :q13, :q14, :q15, :q16, :q17, :q18, :q19, :q20, :q21, :q22, :asa)
    end
end

Thank you!

Error "undefined method `to_datetime'" in sidekiq

Start sidekiq with the command

bundle exec sidekiq -e production -P /path/to/pid/file/tmp/pids/sidekiq.pid -L /path/to/log/file/shared/log/sidekiq.log --daemon

In the log error

2017-06-29T06:59:44.776Z 16181 TID-1jr7pg ERROR: CRON JOB: undefined method `to_datetime' for #<EtOrbi::EoTime:0x0000000a933848>
2017-06-29T06:59:44.776Z 16181 TID-1jr7pg ERROR: CRON JOB: /home/user/.rvm/gems/ruby-2.0.0-p247@script-admin/gems/activesupport-3.2.13/lib/active_support/core_ext/date_time/calculations.rb:141:in `<=>'

error while executing the method /home/user/.rvm/gems/ruby-2.0.0-p247@script-admin/gems/activesupport-3.2.13/lib/active_support/core_ext/date_time/calculations.rb:141:in <=>:

def <=> (other)
  super other.kind_of?(Infinity) ? other : other.to_datetime
end

What can be done with the problem?

Order a model with conditions in Rails (3)

Lets say there is a model called Event. I want to display important and current events first, so i have the attributes important (boolean) and enddate (date).

Now I want to get all events where important == true and where enddate >= today first, all others should be ordered by created_at.

I want to avoid doing events = important_events + not_important_events as this would return an array insted of an activerecord. Does anyone knows an elegant way to order a model in rails?

How to disable SSL Algorithms option in rails with thin server for HTTPS?

I had issue with my HTTPS web application which not open on safari browser.

After that i get feedback from SSL service provider that we need to disable low security Algorithms.

I have my hosted application with thin server not with apache. can some one help me how to disable low security Algorithms with rails thin server.

As per SSL provider he expect me to disable below Algorithms

SHA-1 / RSA WEAK (SLOTH attack )
SHA-1 / DSA WEAK (SLOTH attack )
SHA-1 / ECDSA   WEAK (SLOTH attack )

Slower while generating the XML from the bunch of model object

class GenericFormatter < Formatter
 attr_accessor :tag_name,:objects

 def generate_xml
   builder = Nokogiri::XML::Builder.new do |xml|
   xml.send(tag_name.pluralize) {
   objects.each do |obj|
        xml.send(tag_name.singularize){

            self.generate_obj_row obj,xml
        }                
    end
    }
   end
   builder.to_xml
 end


def initialize tag_name,objects
  self.tag_name = tag_name
  self.objects = objects
end


def generate_obj_row obj,xml
   obj.attributes.except("updated_at").map do |key,value|
     xml.send(key, value)
   end
   xml.updated_at obj.updated_at.try(:strftime,"%m/%d/%Y %H:%M:%S") if obj.attributes.key?('updated_at')
end
 end 

In the above code i have implemented the formatter where I have used the nokogiri XML Builder to generate the XML by manipulating the objects passing out inside the code.It's generated the faster XML when the data is not too large if data is largers like more than 10,000 records then It's slow down the XML to generate and takes atleast 50-60 seconds.

Problem: Is there any way to generate the XML faster,I have tried XML Builders on view as well but did n't work.How i can generate the XML Faster ? Solution should be application on rails 3 and suggestions to optimized above code?

mercredi 28 juin 2017

has_many polymorphic relationship where our _type field is an int?

We have an app in Rails 4 (but soon to be Rails 5) that has a polymorphic log class that we inherited from a Django app.

In a traditional polymorphic relation, the objects would have source_type and source_id, which would be things like 'some_class' and 123.

In our little model, we have content_type and content_id which unfortunately map to two ints, where the int in content_type further points to a ContentType model that -- to further complicate things -- dont map to Rails-ey types ('some_type' but rather django-ey 'some type class'.

It's a mess.

Is there any way to override the value used in looking in a polymorphic association (e.g. instead of using 'some_class', use 11) -- but just for the association? There is an answer for a problem somewhat similar to ours, but it is 4 years old and it overrides association_class. We still use some of this strange Django voodoo elsewhere in our codebase, so overrides feel like they'd cause more problems than solve.

Styling table cell different colors depending on the cell value using erb - ruby on rails

I am currently doing the board for a battleship game on ruby on rails. I am stuck on how to change the color of the table cell (depending which of the values in the array @actions is inside. I tryed using case statement and if'statement in the html.erb but I cant work out the right syntax. And another thing I am wondering: should I do a helper method for this and use it in the html, instead of coding in there?

Here is the repo http://ift.tt/2s2hKxs

Rails database setup Polymorphism

We have to create a request system which will have roughly 10 different types of requests. All of these requests will belong to the 'accounting' aspect of our application. Therefore we've called them "Accounting requests".

All requests share maybe only a few columns and each has up to 20 columns individually.

We started to wonder if having separate tables for each request type would be practical in terms of speed when we start to have to do very complicated joins or queries, for example, fetching ALL requests types into a single table and then sorting it.

Maybe it would be easier to just use Single Table Inheritance since it will have a type column and we'd be using one table to store all 10 accounting request types.

What do you think regarding using STI for this many polymorphic associations and requirements?

Cannot allocate memory in ruby on rails?

I given 2GB RAM. If comes traffic on my website then create problem every time throw exception cannot allocate memory and server process stop.

First rails application: routes.rb not leading to right page(?)

Apologies in advance if this is so basic I probbaly shouldn't post it here. I'm not even sure if the title actually describes the issue. I am just starting to look at Ruby on Rails, and am following this page to set up "my first application": http://ift.tt/IsdtVd

Now, when I get to the point where I add

root 'welcome#index'

Into the routes.rb file and try and access it, it all goes wrong. First I thought it was a permissions issue, but I can access the views/layouts/welcome/index.html.erb file directly in the browser.

I'm so new to this that I haven't got far enough to know what I'm looking for in troubleshooting, hence this post.

When starting the rails server, I do get what looks like errors on restart and hangup signals, but I doubt this is the problem. Output listed here just in case.

=> Booting Puma
=> Rails 5.1.2 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
*** SIGUSR2 not implemented, signal based restart unavailable!
*** SIGUSR1 not implemented, signal based restart unavailable!
*** SIGHUP not implemented, signal based logs reopening unavailable!
Puma starting in single mode...
* Version 3.9.1 (ruby 2.3.3-p222), codename: Private Caller
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop

Loading the root page gives the following server output:

Started GET "/" for 127.0.0.1 at 2017-06-28 13:17:23 +0200
Processing by WelcomeController#index as HTML
  Rendering welcome/index.html.erb within layouts/application
  Rendered welcome/index.html.erb within layouts/application (13.0ms)
Completed 500 Internal Server Error in 3742ms



ActionView::Template::Error (TypeError: Object doesn't support this property or method):
     5:
     6:     <%= csrf_meta_tags %>
     7:
     8:     <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
     9:     <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    10:
    11:     </head>

app/views/layouts/application.html.erb:8:in `_app_views_layouts_application_html_erb___750167210_57076860'

It kind of looks to me as though it does load the index page, but then something else triggers and it's redirected to a page that doesn't work. The content of the page it's directed to (views/layouts/application.html.erb) is:

<!DOCTYPE html>
<html>
  <head>
    <title>Blog</title>

    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

    </head>

  <body>

    <%= yield %>

  </body>
</html>

Content of routes.rb for reference is:

Rails.application.routes.draw do
  get 'welcome/index'

  root 'welcome#index'

  # For details on the DSL available within this file, see http://ift.tt/GVpneB
end

lundi 26 juin 2017

API call works on development, timesout on production heroku

I am using an API which works fine on development but timeouts when I call it from production or heroku run rails console.

I'm doing the following

url = "http://ift.tt/2ubPpFK"
response = RestClient.get url

Locally I get a 200 response, in proudction I get the following:

RestClient::Exceptions::OpenTimeout: Timed out connecting to server from /app/vendor/bundle/ruby/2.3.0/gems/rest-client-2.0.1/lib/restclient/request.rb:731:in rescue in transmit' from /app/vendor/bundle/ruby/2.3.0/gems/rest-client-2.0.1/lib/restclient/request.rb:647:in transmit' from /app/vendor/bundle/ruby/2.3.0/gems/rest-client-2.0.1/lib/restclient/request.rb:145:in execute' from /app/vendor/bundle/ruby/2.3.0/gems/rest-client-2.0.1/lib/restclient/request.rb:52:in execute' from /app/vendor/bundle/ruby/2.3.0/gems/rest-client-2.0.1/lib/restclient.rb:67:in get' from (irb):30 from /app/vendor/bundle/ruby/2.3.0/gems/railties-4.2.6/lib/rails/commands/console.rb:110:in start' from /app/vendor/bundle/ruby/2.3.0/gems/railties-4.2.6/lib/rails/commands/console.rb:9:in start' from /app/vendor/bundle/ruby/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:68:in console' from /app/vendor/bundle/ruby/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in run_command!' from /app/vendor/bundle/ruby/2.3.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in ' from script/rails:6:in require' from script/rails:6:in'

The API does not support ssl, not sure it is has anything to do with it.

Redmine on Turnkey

Having issues after updating Ruby and Rails under Turnkeylinux Redmine. I couldn't run it. Im getting this error : https://prnt.sc/fo7afc

config.ru:1:in new' config.ru:1:in' /usr/local/lib/ruby/gems/2.4.0/gems/passenger-5.1.5/src/helper-scripts/rack-preloader.rb:110:in eval' /usr/local/lib/ruby/gems/2.4.0/gems/passenger-5.1.5/src/helper-scripts/rack-preloader.rb:110:inpreload_app' /usr/local/lib/ruby/gems/2.4.0/gems/passenger-5.1.5/src/helper-scripts/rack-preloader.rb:156:in <module:App>' /usr/local/lib/ruby/gems/2.4.0/gems/passenger-5.1.5/src/helper-scripts/rack-preloader.rb:30:in' /usr/local/lib/ruby/gems/2.4.0/gems/passenger-5.1.5/src/helper-scripts/rack-preloader.rb:29:in `'

[ 2017-06-26 14:45:44.5458 21004/7fc95a96a700 age/Cor/Con/CheckoutSession.cpp:285 ]: [Client 1-2] Cannot checkout session because a spawning error occurred. The identifier of the error is 9b9a9332. Please see earlier logs for details about the error.

dimanche 25 juin 2017

Clear cart ruby on rails

I am a beginner Ruby on rails, I am trying to create a small system of cart. I already rather advance well thanks to stackoverflox and some little tutorial on the web. The problem is that I can not empty my cart without error, I would have to create an action that removes the cookie from my application but I can not. Here is the source of my app that works but without the possibility to empty are basket

view/cart/index.html.erb

>         <h1>Votre panier</h1>
>     <!DOCTYPE html>
>     <html>
>     <head>
>       <title></title>
>     </head>
>     <body>
>     
>     <% total = 0 %>
>     
>     <table>
>       <% @cart.each do |id, quantity| %>
>       <% item = Item.find(id) %>
>       <tr>
>           <td class="images"><%= link_to image_tag(item.image_url, :size => "50x50"), item %></td>
>           <td width="160"><%= item.produit %></td>
>           <td width="160"><%= quantity %></td>
>           <td width="160"><%= number_to_currency(item.prix, unit: "€") %></td>
>           </tr>
>           <% total += quantity * item.prix %>
>     
>           <% end %>
>     
>           <tr>
>               <td colspan="4">Total :</td>
>               <td><%= number_to_currency(total, unit: "€") %></td>
>           </tr>
>       
>     </table>
>
>       # Please, i want empty my cart !
>       <%= link_to 'Back', items_path %>
>     
>     </body>
>     </html>

cart_controller.rb

class CartController < ApplicationController
  def index
    @cart = session[:cart] || {}
  end

  def add
    id = params[:id]
    cart = session[:cart] ||= {}
    cart[id] = (cart[id] || 0) + 1

    redirect_to :action => :index

  end


end

routes.rb

Rails.application.routes.draw do

resources :items      

get 'cart/index'

match ':controller/:action/:id', via: [:get, :post]

root :to => "items#index"

end

samedi 24 juin 2017

Getting "Expected(200) <=> Actual(400 Bad Request)" error for asset_sync gem

I am trying to set up existing rails 3.2.11 project in production environment.

We have used asset_sync gem for syncing assets in s3. But when I ran the precompile command I am getting Expected(200) <=> Actual(400 Bad Request) error. As per the documentation I have added required configuration in the file (application.yml file).

production:
  FOG_DIRECTORY: xxxxxx
  FOG_PROVIDER: xxxxxx
  FOG_REGION: xxxxxx
  ASYNC_UPLOAD_BUCKET: xxxxxx
  AWS_ACCESS_KEY_ID: xxxxxx
  AWS_BUCKET: xxxxxx
  AWS_SECRET_ACCESS_KEY: xxxxxx

As per the doc created separate initializer file (config/initializers/asset_sync.rb)

AssetSync.configure do |config|
  config.fog_provider = 'AWS'
  config.aws_access_key_id = ENV['AWS_ACCESS_KEY_ID']
  config.aws_secret_access_key = ENV['AWS_SECRET_ACCESS_KEY']
  config.fog_directory = ENV['FOG_DIRECTORY']
  config.fog_region = ENV['FOG_REGION']
end

When I checked the response for the compilation it is showing message

<Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message>  

Can any one let me know how can I fix this issue.

How make Jquery_chained.js choose the id in Rails?

After added the jquery_chained.js and setup everything works fine, but on the save the eletronic_id inside container table still nil.

Someone know why and how to fix it?

I've tried to change on the js to call to see if fix, but did not worked. $('select#eletronic_name').chainedTO('select#block_name');

http://ift.tt/1wGUPXx

 model container

        belons_to :block
        belongs_to :eletronic

        end



    $(document).ready(function(){

       $('#eletronic').chained('#block');

    }); 

    ContainersController

     # creating data arrays for selects
        @blocks = Block.all
        @blocks_for_dropdown = []
        @blocks.each do |i|
          @blocks_for_dropdown << [i.category, i.id]
        end

    # creating data arrays for selects
        @eletronics = Eletronic.all
        @eletronics_for_dropdown = []
        @eletronics.each do |i|
        @eletronics_for_dropdown << [i.item, i.id, {class: i.block.id}]
        end



    end




container new.html.erb

  <%= select("block", "name", options_for_select(@blocks_for_dropdown), {prompt: 'Select'}, {class: 'chained-select', :id => 'block'}) %>



  <%= select("eletronic", "name", options_for_select(@eletronics_for_dropdown), {prompt: 'Select'}, {class: 'chained-select', :id =>'eletronic'}) %>

vendredi 23 juin 2017

How do you remove the edit button in an active admin show

I want to remove the edit button on active admin show pages for any record except for those where the month and year equal the current month and year.

I was able to do that in the index with

  if (es.month == Date.today.strftime("%m").to_i) && (es.year == Date.today.strftime("%Y").to_i )
    span link_to 'Edit', "/executive_summaries/#{es.id}/edit"
  end

My executive_summaryies.rb includes

ActiveAdmin.register Executive::Summary do
  menu :parent => 'Reports'

  config.batch_actions = true

 . . .

  action_item :only => :show do
     link_to_function("#{ActiveAdmin::Iconic.icon(:document_stroke)} Print Executive Summary".html_safe, "javascript:print()")

  end

 . . .

 controller do

 . . . 

    def edit
      @run_js_functions = %w(ExecutiveSummaries.init)
    end

    def show
      @run_js_functions = %w(ExecutiveSummaries.accordion)
    end

    . . . 

end

The way the code is currently, the edit button shows in the titlebar (by default I believe) and there is a print button next to it. (From the code in the show above).

How can I just show the edit button for records that are for the current month and year on the show/view page?

Validation is not working if integer value of old attribute is same as that of new attribute

I've a model Cart having has_many relationship with cart_items.

# cart.rb:
  accepts_nested_attributes_for :cart_items, allow_destroy: true
  has_many :cart_items, dependent: :destroy, inverse_of: :cart

# cart_item.rb:
  validates :quantity, presence: true, numericality: { greater_than: 0 }

# Controller code:

  def update
    current_cart.assign_attributes(params[:cart])
    .....
    current_cart.valid?
  end

While updating cart_items, if integer (to_i) value of quantity is same as old value then validation is not working.

For example, If old value of quantity is 4, now new value is updated to 4abc then quantity validation is not working and record is considered as valid.

Although, if new value is updated from 4 to 5abc then it shows a validation error, as expected.

Any suggestions why this all is happening?

EDIT:

Here's the output of rails console:

[3] pry(#<Shopping::CartsController>)> cart
=> #<Cart id: 12, created_at: "2017-06-22 13:52:59", updated_at: "2017-06-23 08:54:27">

[4] pry(#<Shopping::CartsController>)> cart.cart_items
[#<CartItem id: 34201, cart_id: 12, quantity: 4, created_at: "2017-06-23 05:25:39", updated_at: "2017-06-23 08:54:27">]

[5] pry(#<Shopping::CartsController>)> param_hash
=> {"cart_items_attributes"=>{"0"=>{"id"=>"34201", "quantity"=>"4abc"}}}
[6] pry(#<Shopping::CartsController>)> cart.assign_attributes param_hash
=> nil
[7] pry(#<Shopping::CartsController>)> cart.valid?
=> true

Here, previous quantity of cart_item is 4 and new value is 4abc, but still the cart is validated.

jeudi 22 juin 2017

when installing bundle install error of therubyracer

i have install nodejs on ubuntu 14.04 ..but when installing bundle install i have get error

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

An error occurred while installing therubyracer (0.12.2), and Bundler cannot continue. Make sure that gem install therubyracer -v '0.12.2' succeeds before bundling.

Audits log with nested models

I'm using the gem audited to track database changes. I want to show the user a audition log, with all audits ordered by created_at. The problem is some audits are related to nested models, for example, a Person can have one address (and accepts_nested_attributes_for it). In this case there is no sense in showing the address changes in the Audits log, since it cannot be identified by the user, the address changes should register an Audit for the Person and then I should be able to find the children audits from it.

The solution I have found is to force a parent update from the child model so and Audit will be crated for the parent. Now, the problem is, there is no way to find the children Audits from this parent Audit. When the user click an Person Audit from the log list, I want to show him all changes that happened to the Person and also to it's address.

With the audited gem is possible to do

audited :associated_with => :person

but the audit will be associated to the parent model, and not to any Audit, so there is no way to tie together the parent and children audits. I can only access the entire list of audits for the address, and can't find the one that was associated to the audit I'm currently showing him.

Is there a way to accomplish this with the audited gem (hacks are welcome) or is there other gem that is able to do it (like papertrail) ?

Rails Zoho configuration sending mails via console but not from mailer class

Ce résumé n'est pas disponible. Veuillez cliquer ici pour afficher l'article.

mercredi 21 juin 2017

Rails mount twice in routes.rb

I need to mount two times in my routes.rb file. Since I added ForestLiana, the second one (Facebook Messenger) is not working.

Any idea how I can solve this issue and use both?

Rails.application.routes.draw do
  mount ForestLiana::Engine => '/forest'
  resources :cards
  resources :bot_users
  resources :core_bots
  resources :letters
  devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks", registrations: 'registrations' }

  mount Facebook::Messenger::Server, at: 'listen'
end

how to read a CSV File with Capl programm?

How to call Csv file with capl and individual column programs Example for CSV-file.

How to find a object and insert it in a database

I’m trying to pick up the shop_id and subscription_id from a cart and insert/save them into the purchase database.

I have a cart, line_items and subscriptions.

And this is how I’m trying to do this:

@purchase = @cart.line_items.build 
@purchase = current_shop.purchases.build(purchase_params)
@purchase.save!

I got the shop_id, but the subscription_id for some reason is nil.

Any ideas what maybe wrong?

Update 1

def purchase_params
  params.permit(:subscription_id, :shop_id, :created_at, :updated_at, :id, :cart_id)
end


Started POST "/line_items?subscription_id=1" for ::1 at 2017-06-18 16:45:12 +0300
Processing by LineItemsController#create as HTML
Parameters:  {"authenticity_token"=>"dUonc4AnCvFTuK1b+TAKho/kmpvl7XaOM7SGcNalzdQV1+CqhY4 p7znDiL/TV12pVKeDTqlR7j5NL65X1S/75A==", "subscription_id"=>"1"}
Cart Load (0.1ms)  SELECT  "carts".* FROM "carts" WHERE "carts"."id" =   ? LIMIT ?  [["id", 14], ["LIMIT", 1]]
(0.1ms)  begin transaction
SQL (0.4ms)  INSERT INTO "carts" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", 2017-06-18 13:45:12 UTC], ["updated_at", 2017-06-18 13:45:12 UTC]]
 (0.7ms)  commit transaction
 Subscription Load (0.2ms)  SELECT  "subscriptions".* FROM "subscriptions" WHERE "subscriptions"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  (0.1ms)  begin transaction
 SQL (0.6ms)  INSERT INTO "line_items" ("subscription_id", "cart_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["subscription_id", 1], ["cart_id", 18], ["created_at", 2017-06-18 13:45:12 UTC], ["updated_at", 2017-06-18 13:45:12 UTC]]
 (0.9ms)  commit transaction
Redirected to http://localhost:3000/carts/18
Completed 302 Found in 21ms (ActiveRecord: 3.2ms)

I'm implementing braintree payments via the following create method and this is where I have the small peace of code:

def create
  current_shop.has_payment_info?
    @result = Braintree::Transaction.sale(
            amount: @cart.total_price,
            payment_method_nonce: params[:payment_method_nonce],
            customer: {
              first_name: current_shop.first_name,
              last_name: current_shop.last_name,
              company: current_shop.shop_name,
              email: current_shop.email,
              phone: current_shop.phone_number,
              website: current_shop.web_page
            },
            options: { store_in_vault: true })


      if @result.success?
    current_shop.update(braintree_customer_id:    @result.transaction.customer_details.id) unless  current_shop.has_payment_info?


    @purchase = @cart.line_items.build 
    @purchase.save!
    @purchase = current_shop.purchases.build(purchase_params)
    @purchase.save!
    @cart.destroy
    redirect_to front_index_path, notice: 'Your transaction was succesfully processed'
  else
gon.client_token = generate_client_token
redirect_to :back, :notice => 'Something went wrong while processing your transaction. Please try again!'
  end
end

Update 2

class Purchase < ApplicationRecord
    belongs_to :shop
    belongs_to :cart
end

class Shop < ApplicationRecord
  has_many :items
  has_many :purchases
  has_many :subscriptions
end


class Subscription < ApplicationRecord
    has_many :line_items
    belongs_to :shop
end

class Cart < ApplicationRecord
  has_many :line_items, dependent: :destroy
  has_many :purchases
end

class LineItem < ApplicationRecord
  belongs_to :subscription
  belongs_to :cart
end

mardi 20 juin 2017

Ruby: Datetime to UTC conversion

I am trying to convert the below date and time combination to UTC

from_date: "2017-06-19",from_time: "14:00" to_date: "2017-06-19", to_time: "23:00" Timezone: EDT

I am using below piece of code for conversion

Date.parse(dt).to_datetime + Time.parse(t).utc.seconds_since_midnight.seconds

And it gives the wrong date value for the to_date & to_time combination.

Output:

Date.parse(from_date).to_datetime + 
Time.parse(from_time).utc.seconds_since_midnight.seconds
 => **Mon, 19 Jun 2017 18:00:00 +0000**

Date.parse(to_date).to_datetime + Time.parse(to_time).utc.seconds_since_midnight.seconds
 => **Mon, 19 Jun 2017 03:00:00 +0000**

Above conversion should give "Tue, 20 Jun 2017 03:00:00 +0000" instead.

How we can upload multiple images on cloudinairy in slots with rails

My requirement is to upload multiple images on cloud in slots. For example i have 100 images in array then images goes in 3 - 3 slots on cloudinairy and and at the time of upload i have any error like time out then it handle exception and goes to upload next image of same slot and this process continue until all images will uploaded.

lundi 19 juin 2017

Ruby on rails, PG::InvalidParameterValue: ERROR:

Every time I try to run bundle exec rake db:create db:migrate I get this error, anyone know how to fix it?

PG::InvalidParameterValue: ERROR: new encoding (UTF8) is incompatible with the encoding of the template database (SQL_ASCII) HINT: Use the same encoding as in the template database, or use template0 as template. : CREATE DATABASE "ruby-getting-started_development" ENCODING = 'unicode' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in async_exec' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:inblock in execute' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract_adapter.rb:484:in block in log' /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.8/lib/active_support/notifications/instrumenter.rb:20:ininstrument' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract_adapter.rb:478:in log' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql/database_statements.rb:154:inexecute' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql/schema_statements.rb:78:in create_database' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/postgresql_database_tasks.rb:15:increate' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:93:in create' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:107:inblock in create_current' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:276:in block in each_current_configuration' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:275:ineach' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:275:in each_current_configuration' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:106:increate_current' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/railties/databases.rake:17:in block (2 levels) in <top (required)>' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:inblock in execute' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:in each' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:inexecute' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/task.rb:194:in block in invoke_with_call_chain' /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/monitor.rb:214:inmon_synchronize' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/task.rb:187:in invoke_with_call_chain' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/task.rb:180:ininvoke' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:152:in invoke_task' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:inblock (2 levels) in top_level' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in each' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:inblock in top_level' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:117:in run_with_threads' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:102:intop_level' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:80:in block in run' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:178:instandard_exception_handling' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:77:in run' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/exe/rake:27:in' /usr/local/rvm/gems/ruby-2.3.0/bin/rake:23:in load' /usr/local/rvm/gems/ruby-2.3.0/bin/rake:23:in' /usr/local/rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in eval' /usr/local/rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in' Couldn't create database for {"adapter"=>"postgresql", "encoding"=>"unicode", "pool"=>5, "database"=>"ruby-getting-started_development"} PG::InvalidParameterValue: ERROR: new encoding (UTF8) is incompatible with the encoding of the template database (SQL_ASCII) HINT: Use the same encoding as in the template database, or use template0 as template. : CREATE DATABASE "ruby-getting-started_test" ENCODING = 'unicode' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in async_exec' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:inblock in execute' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract_adapter.rb:484:in block in log' /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.8/lib/active_support/notifications/instrumenter.rb:20:ininstrument' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract_adapter.rb:478:in log' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql/database_statements.rb:154:inexecute' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql/schema_statements.rb:78:in create_database' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/postgresql_database_tasks.rb:15:increate' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:93:in create' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:107:inblock in create_current' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:276:in block in each_current_configuration' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:275:ineach' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:275:in each_current_configuration' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:106:increate_current' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/railties/databases.rake:17:in block (2 levels) in <top (required)>' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:inblock in execute' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:in each' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:inexecute' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/task.rb:194:in block in invoke_with_call_chain' /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/monitor.rb:214:inmon_synchronize' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/task.rb:187:in invoke_with_call_chain' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/task.rb:180:ininvoke' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:152:in invoke_task' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:inblock (2 levels) in top_level' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in each' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:inblock in top_level' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:117:in run_with_threads' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:102:intop_level' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:80:in block in run' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:178:instandard_exception_handling' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/lib/rake/application.rb:77:in run' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/exe/rake:27:in' /usr/local/rvm/gems/ruby-2.3.0/bin/rake:23:in load' /usr/local/rvm/gems/ruby-2.3.0/bin/rake:23:in' /usr/local/rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in eval' /usr/local/rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in' Couldn't create database for {"adapter"=>"postgresql", "encoding"=>"unicode", "pool"=>5, "database"=>"ruby-getting-started_test"} rake aborted! ActiveRecord::NoDatabaseError: FATAL: database "ruby-getting-started_development" does not exist /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:661:in rescue in connect' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:651:inconnect' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:242:in initialize' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:44:innew' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:44:in postgresql_connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:438:innew_connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:448:in checkout_new_connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:422:inacquire_connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:349:in block in checkout' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:348:incheckout' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:263:in block in connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:262:inconnection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:571:in retrieve_connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_handling.rb:113:inretrieve_connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_handling.rb:87:in connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/migration.rb:916:ininitialize' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/migration.rb:823:in new' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/migration.rb:823:inup' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/migration.rb:801:in migrate' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:137:inmigrate' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/railties/databases.rake:44:in block (2 levels) in <top (required)>' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/exe/rake:27:in' /usr/local/rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in eval' /usr/local/rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in' PG::ConnectionBad: FATAL: database "ruby-getting-started_development" does not exist /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:651:in initialize' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:651:innew' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:651:in connect' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:242:ininitialize' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:44:in new' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:44:inpostgresql_connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:438:in new_connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:448:incheckout_new_connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:422:in acquire_connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:349:inblock in checkout' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:348:in checkout' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:263:inblock in connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:262:in connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:571:inretrieve_connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_handling.rb:113:in retrieve_connection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/connection_handling.rb:87:inconnection' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/migration.rb:916:in initialize' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/migration.rb:823:innew' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/migration.rb:823:in up' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/migration.rb:801:inmigrate' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/tasks/database_tasks.rb:137:in migrate' /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.8/lib/active_record/railties/databases.rake:44:inblock (2 levels) in ' /usr/local/rvm/gems/ruby-2.3.0/gems/rake-12.0.0/exe/rake:27:in <top (required)>' /usr/local/rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:ineval' /usr/local/rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in `' Tasks: TOP => db:migrate (See full trace by running task with --trace)

Get single record from has_many using eager-loading in include

I'm new to rails and stuck between eager-loading from last 2 days. I have two models Car and Images with Car has_many :images association. and I have made an api which returns json array of cars with their images. I want single image instead all images from association. I'm using like:

Car.where(:company=>"BMW").as_json(:include=> {:images})

This will return all the cars with their all images. I want all cars with their single image instead of all images array.

How to achieve deep linking in Ruby on Rails

How can we achieve deep linking of ios applications on Rails server.

I am not sure how a deep linking works, But in my understanding it should work like this:

  1. There would be one URI which would be shared among users eg: http://ift.tt/2sJSNuQ
  2. When request would come from this URL rails will open this application in the device if the application is installed in device.
  3. When request would come from this URL rails will open App Store in browser if the application is not installed in device.

I came across similar code in PHP How can I achieve that in Rails:

   public function getShare(Request $request) {
    try {

        $app_name = $request->input('app_name', ‘URLSCHEME, Dev will give’);
        $shared_on = $request->input('shared_on', 'facebook');
        $shared_from = $request->input('shared_from', 'web');
        $shared_id = $request->input('shared_id', '0');
        $shared_by = $request->input('shared_by', '0');
        $app_store_id = '';
        $message = 'ok';


        $rules = array(
            // marketplace
            'app_name' => 'sometimes|string',
            // facebook, twitter
            'shared_on' => 'sometimes|string',
            // web , ios 
            'shared_from' => 'sometimes|string',
            //product_id' 
            'shared_id' => 'required|integer',
            // user_id
            'shared_by' => 'sometimes|integer',
        );
        $validation = Validator::make($request->all(), $rules);


        if ($validation->fails()) {
            $message = trans('messages.invalid_request');
        }
    } catch (Exception $e) {
        $message = trans('messages.exception_msg');
    }

    $deeplink = $app_name . "://applinks"
            . "?shared_on=" . $shared_on
            . "&shared_from=" . $shared_from
            . "&shared_id=" . $shared_id
            . "&shared_by=" . $shared_by
            . "&message=" . $message;

    $return_url = url('student/dashboard')
            . "?shared_on=" . $shared_on
            . "&shared_from=" . $shared_from
            . "&shared_id=" . $shared_id
            . "&shared_by=" . $shared_by
            . "&message=" . $message;



   $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
   if(stripos($ua,'android') !== false) { 

        $return_url = 'http://ift.tt/2tjG9zS';
    }
    else if(stripos($ua,'iPhone') !== false || stripos($ua,'iPad') !== false) { 
        $return_url = 'http://ift.tt/2sJYh91';
    }



    $html = '<html>
                <head>
                    <meta property="og:title" content="' . $app_name . '" />
                    <meta property="og:type" content="website" />
                    <meta property="al:android:package" content="' . $package . '" />
                    <meta property="al:android:url" content="' . $deeplink . '" />
                    <meta property="al:android:app_name" content="' . $app_name . '" />
                    <meta property="al:ios:url" content="' . $deeplink . '" />
                    <meta property="al:ios:app_store_id" content="' . $app_store_id . '" />
                    <meta property="al:ios:app_name" content="' . $app_name . '" />
                    <meta property="al:web:url" content="' . $return_url . '" />
                    <!-- Other headers -->';

    if(!$this->isMobileDevice())
    {
        $deeplink = $return_url;
    }

    $html = $html . "<script>
                    window.onload = function() {
                    <!-- Deep link URL for existing users with app already installed on their device -->
                        window.location = '" . $deeplink . "';
                    <!-- URL  for new users to download the app -->
                        setTimeout(\"window.location = '" . $return_url . "';\", 3000);
                    }
                </script>";

    $html = $html . '</head>
                <!-- Other HTML content -->';
    $html = $html . "Try opening <a id='deeplink' href='$deeplink'>app</a> ...";
    $html = $html . '</html>';
    echo $html;
    exit();
}

samedi 17 juin 2017

Rails 5 Active Record Record Invalid Error

I have two Rails model namely Invoice and Invoice_details. An Invoice_details belongs to Invoice, and an Invoice has many Invoice_details. I'm not able to save Invoice_details via Invoice model using accepts_nested_attributes_for in Invoice.

I get the following error :

(0.2ms)  BEGIN
(0.2ms)  ROLLBACK
Completed 422 Unprocessable Entity in 25ms (ActiveRecord: 4.0ms)         
ActiveRecord::RecordInvalid (Validation failed: Invoice details invoice must exist):
app/controllers/api/v1/invoices_controller.rb:17:in `create'

Below is the code snippet for invoice.rb :

class Invoice < ApplicationRecord
  has_many :invoice_details
  accepts_nested_attributes_for :invoice_details
end

The code snippet for invoice_details.rb :

class InvoiceDetail < ApplicationRecord
  belongs_to :invoice
end

The Controller code :

class Api::V1::InvoicesController < ApplicationController
  respond_to :json

  def index
    comp_id = params[:comp_id]
    if comp_id
      invoices = Invoice.where(:company_id => comp_id)
      render json: invoices, status: 201
    else
      render json: { errors: "Company ID is NULL" }, status: 422
    end
  end

  def create
    Rails.logger.debug invoice_params.inspect
    invoice = Invoice.new(invoice_params)
    if invoice.save!
      render json: invoice, status: 201
    else
      render json: { errors: invoice.errors }, status: 422
    end
  end

  def invoice_params
    params.require(:invoice).permit(:total_amount,:balance_amount, :customer_id, invoice_details_attributes:[:product_id])
  end
end

The raw JSON data passed to the controller :

{
    "invoice":{
        "total_amount":"100",
        "balance_amount":"0",
        "invoice_details_attributes":[{
            "product_id":"4"
        }]
    }
}

Why show undefined on rails select?

i have a ajax select on a rails app that is showing undefined on select like the screeshot attached

i changed the order to fix but if i remove the order did not show, and if i put create_at or by name asc show this undefined

someone know why?

the on controller is:

 def index
          genders = Gender.where(block_id: params[:block_id]).select('id, gender').order('created_at asc')
          render json: genders
        end

in the view is:

<%=dynamic_collection_select :product, :gender_id, :category, [], :id, :gender, { include_blank: false, submit_with_form: true, :prompt=> 'Select' }, { class: 'form-control select_item' } %>

enter image description here

vendredi 16 juin 2017

How can I make follow form work with a list

I have a relationship model that follow users back n forth now it works very well when I use it in users#show in my view just like this screenshot

enter image description here

now this works good but what I have is a list of users.. and with that list I want to render similar type of follow form next to every item in list

here is the screenshot for reference

enter image description here

but of course this doesn't work because in my relationship controller I am finding user/amitian to follow with their id in params[:id] as in show page i have it but in my list page i don't

here is the code in controller for reference

def create
    @amitian = Amitian.find(params[:followed_id])
    current_amitian.follow(@amitian)
     respond_to do |format|
      format.html { redirect_to @amitian }
      format.js
    end
  end

  def destroy
    @amitian = Relationship.find(params[:id]).followed
    current_amitian.unfollow(@amitian)
     respond_to do |format|
      format.html { redirect_to @amitian }
      format.js
    end
  end

is there any solution for this so that I can render a follow_form in my listpage it doesn't matter even if i have to render a new follow_form.. it just i want follow mechanism to work even from list page rather than only from show page of every user.

how to get params[:id] of @post when you have layout: false

I am new to rails and want to create a model where every Post#show comes into a bootstrap-modal not into a separate show.html.erb page.. in my show controller i have something like this

def show 
  @confessions = Confession.find(params[:id])
  @comment = Confessioncomment.where(confession_id: @confessions).paginate(page: params[:page], per_page: 5).order('created_at ASC')
end

I am getting my @confessions from the params[:id] as of now to show the exact post I clicked on

but what I want is not to show a separate show page but to load everything in my bootstrap-modal on the same page.

I know I can use layout :false to tell that show will have no layout but I am not sure how to use it.. or if there is any other way to do this, please help.

how can I show post on same page rather than loading a new page from controller.

any ideas ?

Rails 3 #update_attributes

I'm working on a Rails 4 app that was previously upgraded from Rails 3. I haven't worked much Rails 3 before. I came across this something like this user.update_attributes({ attr => bulk_update_params[attr] }, :as => :admin). Rails 4 currently complains that update_attributes only accepts 1 argument and not 2.

I tried merging the as: :admin by doing user.update_attributes({ attr => bulk_update_params[attr] }).merge(as: :admin) but then i get greeted with something like "as" is not a known attribute".

Not entirely sure but how do I deal with the as: admin part? Is it safe to remove it entirely or there's a way to pass as: :admin to the original user.update_attributes({ attr => bulk_update_params[attr] }, :as => :admin) in Rails 4?

I think it has something to do with attr_accessible and strong_params just not sure how to work with it in Rails 4 now. Any ideas?

jeudi 15 juin 2017

Getting error while migrating db in ruby on rails project on windows 7, with ruby 2.3.3 and rails 4.2.5.2

I am getting below errors on prelauch project on github. I have install postgres db but i am not getting which gem is having PGconn , PGresult and PGerror.

The PGconn, PGresult, and PGError constants are deprecated, and will be removed as of version 1.0.   You should use PG::Connection, PG::Result, and PG::Errenter code hereor instead, respectively.enter code here

Called from C:/Ruby23/lib/ruby/gems/2.3.0/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:240:in `load_dependency
'
== 20130127063936 DeviseCreateAdminUsers: migrating ===========================
-- create_table(:admin_users)
   -> 0.2293s
-- add_index(:admin_users, :email, {:unique=>true})
   -> 0.0638s
-- add_index(:admin_users, :reset_password_token, {:unique=>true})
   -> 0.0658s

== 20130127063936 DeviseCreateAdminUsers: migrated (0.3603s) ==================
 
rake aborted!
LoadError: cannot load such file -- bcrypt_ext
D:/Projects/prelaunchr/db/migrate/20130127063936_devise_create_admin_users.rb:5:in `migrate'
C:in `migrate'
LoadError: cannot load such file -- 2.3/bcrypt_ext

D:/Projects/prelaunchr/db/migrate/20130127063936_devise_create_admin_users.rb:5:in migrate' C:in migrate' Tasks: TOP => db:migrate (See full trace by running task with --trace)

Ruby version: 2.3.3
Rails version : 4.2.5.2

Ruby on Rails - Security Notifications

I'm working on a project with ROR framework and the gem "Devise" for the authentication.

Actually i have 3 model of users :

  • User
  • Admin
  • Company

I would like to know if there is a way to get the user's account activities with the time and ip (i got it with devise):

When the user login, logout, fail login, change password, unlock account etc ...

Shall i build a new model : security_notifications which is associated with User model, and override devise Controllers to create the notification after every actions ? Or there is a better method ?

Thanks,

Put gem class into namespace

To my Rails Gemfile I added a new Gem. It get's used like this:

Email::Client

The issue i'm having right now is that I also have a class in my Rails-App that's called Email. Now sometimes when I try to initialize it I get the following error:

Email.new # >> undefined method 'new' for Email:Module

Probably because Email is a Module in the Gem. How can fix this issue? Is there a way to namespace the Gem Module? I don't want to rename the Email-Class.

mercredi 14 juin 2017

rails cannot create a new item

I am working on creating a small rails app, and I have ran into a problem that I believe is in the backend of my database, but I don't know how to solve it. Ultimately what is happening is if I try to go to my my new url, I get an error stating PG::UndefinedTable: ERROR: relation "caves" does not exist LINE 8: WHERE a.attrelid = '"caves"'::regclass

All I am trying to do us create a new cafe I go to localhost:3000/cafes/new but for some really annoying reason, caves somehow somewhere got in the mix and I don't know how to get around this.

My controller is essentially below. (the rest of the items in my controller are empty methods at this point)

  def new
    @cafe = Cafe.new
  end

  def create
    @cafe = Cafe.new(cafe_params)
  end

  private

  def cafe_params
    params.require(:name, :description)
  end

My schema table is

  enable_extension "plpgsql"

  create_table "cafes", force: :cascade do |t|
    t.string "name"
    t.text "description"
  end

  create_table "users", force: :cascade do |t|
    t.string "first_name"
    t.string "last_name"
    t.string "email"
    t.integer "age"
  end

I have two empty models right now one called user.rb and the other cafe.rb

This is where I get really confused because there is no cave relation in my model.

class Cafe < ApplicationRecord
end

Thats about where I am. Would anyone know what I could do with this? I'm thinking that possibly there is a duplicate database somewhere and it needs to be destroyed. I've tried a rake db:drop + rake db:create + rake db:migrate route with what I have, but no luck. I know there is a way to open up my database through straight up psql, and I think that may be the way into really truly debugging this problem. (i've seen it done once, but don't remember how to do it, let alone only know active record, not sql)

Does anyone know whats going on here? Or does anyone know how to get into psql and how to find something like this?

I really do appreciate it.

Passing a default parameter to a Rails 3 route makes it fail to match the route in the controller test

I'm upgrading an old application for a non-profit, and I've having issues with some routes and controller tests on Rails 3.0.20 (Rails 2 -> 3 is the first of many upgrades I need to make :( )

This is my route definition:

match "new/tribes" => "news#tribes",
  as: "en_news_tribes",  
  defaults: {
    page_slug: 'tribes',
    language_id: 3,
    section_id: 4
  }

The idea is that when the controller is called the parameters will include the default values for page_slug, language_id and section_id

In my controller test (TestUnit based) the action is invoked like this:

get :tribes, { section_id: 4, language_id: 4, tribe_id: @loc_tribe.tribe.id }

But this produces this routing exception:

ActionController::RoutingError: No route matches {:section_id=>4, :language_id=>3, :tribe_id=>1, :controller=>"news", :action=>"tribes"}

Only if I specify all the default parameters does it find a route (and the test passes):

get :tribes, { section_id: 4, language_id: 4, tribe_id: @loc_tribe.tribe.id, page_slug: 'tribes' }

If the parameters I pass don't match the default parameter values specified in config/routes.rb it doesn't find the route.

i.e. This doesn't work:

get :tribes, { section_id: 4, language_id: 4, tribe_id: @loc_tribe.tribe.id, page_slug: 'Abc123' }

So it seems like these default values are in fact behaving as routing constraints?

I hope someone can help! I am at the start of a long road in getting this application to Rails 5 ;)

How to cache a ActiveRecord model object which contains carrierwave uploader to Redis

I have a user model which has a carrierwave uploader for storing ths users profile picture

class User < ActiveRecord::Base
    mount_uploader :profilepic, LogoUploaderUploader

I want to cache this User object in redis. While caching I call the to_json method on the activerecord object which converts the profilepic field in the user object to a hash containing the url of the image

user={id:1, username: "sam", profilepic: {url:"path_to_image.jpg"}}

This part is fine and I can store it in redis. But the trouble comes when I retrieve the data from redis and try to convert it to a ActiveRecord object like the following

user=User.new(json_data)

The profilepic field comes null. Looks like it is not able to deserialize the profilepic hash profilepic: {url:"path_to_image.jpg"}to a proper value.

Is there anyway I can get back the proper value for profilepic after saving to redis.

Why Page and Action Caching has been removed from Rails 4?

Why Page Caching and Action Caching are removed from Rails 4.

How do we achieve the caching now after Rails 4 ?

mardi 13 juin 2017

Include select scope in outer join includes

Rails 3, I want to include a select scope in a join clause. Here's the code I have:

require 'logger'
require 'active_record'
require 'pg'

ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
  create_table :users, :force => true do |t|
    t.string :name
  end

  create_table :properties, :force => true do |t|
    t.integer :user_id, unique: true
    t.string :line1
    t.string :line2
  end
end

class User < ActiveRecord::Base
  attr_accessible :name
  has_one :property
end

class Property < ActiveRecord::Base
  belongs_to :user
  attr_accessible :address, :line1, :line2
  default_scope :select => "#{table_name}.*, #{table_name}.line1 || ', ' || #{table_name}.line2 AS address"
end

u = User.new(name: :a)
p = Property.new(line1: :y, line2: :z, user: u)
p.user = u
p.save

This line generates the following sql:

User.first.property.address

User Load (0.1ms)  SELECT "users".* FROM "users" LIMIT 1
Property Load (0.1ms)  SELECT properties.*, properties.line1 || ', ' || properties.line2 AS address FROM "properties" WHERE "properties"."user_id" = 1 LIMIT 1

But this line doesn't include the custom select scope with the computed column:

User.includes(:property).where('properties.address=?', 'y, z').first.property.address

SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, "properties"."id" AS t1_r0, "properties"."user_id" AS t1_r1, "properties"."line1" AS t1_r2, "properties"."line2" AS t1_r3 
FROM "users" 
LEFT OUTER JOIN "properties" ON "properties"."user_id" = "users"."id" 
WHERE (properties.address='y, z') 
LIMIT 1

Any way to get it to do something like this?

LEFT OUTER JOIN (SELECT properties.*, properties.line1 || ', ' || properties.line2 AS address FROM "properties") AS "properties" ON "properties"."user_id" = "users"."id" 
WHERE (properties.address='y, z') 

How can I create ActiveRecord for the following sql

How can I create an ActiveRecord Query for the following Sql query

SELECT device1.*
FROM devices device1
WHERE device1.id = (SELECT MAX(device2.id)
                 FROM devices device2
                 WHERE device2.user_id = device1.user_id);

I have Device model with user_id column

I dont want to user find_by_sql because it returns Array instead ActiveRecord Array

How to validate email is real or fake in Rails?

I have a problem I need write validator in rails to checking an email is real or fake? I try to research but nothing. Can someone help me? Thanks !

lundi 12 juin 2017

My User_id is updated to nil every time I refresh my page in Rails

I know what is causing this issue, but can't find the working alternative of it. I will describe the problem and hope for a good answer.

So, I have a bootstrap modal in which i have a form. that form _for is calling GalleryController#create method.. this is my modal -->

#gallery_create_modal.modal.fade.m{'tabindex':-1 , 'role':'dialog','aria-labelledby':'creategallery'}
    .modal-dialog.modal-lg{'role':'document'}
        .modal-content
            =form_for @gallery , html: {multipart: true}  do |f|

                ...content

                =f.submit 'Upload' , class: 'btn btn-primary'           

and here is my gallery controller

class GalleriesController < ApplicationController

before_action :authenticate_amitian!

def create
@gallery = current_amitian.create_gallery(gallery_params)

end

private

def gallery_params
params.require(:gallery).permit(:g1,:g2,:g3,:g4,:g5,:g6,:amitian_id)
end

end

upto this point if I run the code it returns error saying first element of form can't be empty or nil... means my @gallery is nil

this is because my modal is in my Amitians#show page so to solve this I had to initialize my @gallery inside Amtians#show method like this -->

class AmitiansController < ApplicationController

before_action :authenticate_amitian!, except: [:show]

def index
...content
end

def show
....
@gallery = current_amitian.build_gallery
....

end

This takes away the error but everytime I refresh my page after upload.. it updates my sql table's Gallery.amitian_id to NULL

I can't seem to find a sol. please help. Thank you.

Getting all users from db that participated for an activity

I am currently facing the following problem: Users are able to create activities. Other users have the possibility, to participate the activity. I now want that the users, which already participated to an activity are going to be listed in the view of the activity. So what I try is to show all the users that participated for an activity in the show method of the activity_controller with an activity_id.

The relations of the models are as follows:

 class Activity < ActiveRecord::Base
  has_many :users, through: :participations
  belongs_to :user
  has_many :participations
  has_many :reviews

end


 class Participation < ActiveRecord::Base
  belongs_to :user
  belongs_to :activity
  has_many :activities
end




 class User < ActiveRecord::Base
  has_many :activities
  has_many :participations
  has_many :reviews

end

My activity controller ist doing the following:

class ActivitiesController < ApplicationController
  before_action :set_activity, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:show]

  def index
    @activities = Activity.all
  end

  def show
    @participated = Participation.where("activity_id = ? AND user_id = ?", @activity.id, current_user.id).present? if current_user
    @reviews = @activity.reviews
    @hasReview = @reviews.find_by(user_id: current_user.id) if current_user

    @participant = Participation.where (:activity_id == 'activity_id')
  end



  def new
    @activity = current_user.activities.build
  end

  def create
    @activity = current_user.activities.build(activity_params)

    if @activity.save

      redirect_to edit_activity_path(@activity), notice: "We want to give you a warm welcome!"

    else
      render :new, notice: "Something seems to be missing!"
    end
  end

  def edit
    if current_user.id == @activity.user.id
      redirect_to root_path
    end
  end

  def update
    if @activity.update(activity_params)
      redirect_to edit_activity_path(@activity), notice: "Updated!"
    else
      render :edit
    end
  end

  def destroy
    @activity = Activity.find(params[:id])

    if @activity.destroy
      redirect_to activities_path, notice: "Deleted!"
    end
  end

  private

  def set_activity
    @activity = Activity.find(params[:id])
  end


  def activity_params
    params.require(:activity).permit(:activity_name,
                                     :activity_starttime,
                                     :activity_duration,
                                     :activity_intensity,
                                     :activity_distance,
                                     :activity_topography,
                                     :activity_address,
                                     :activity_track,
                                     :activity_summary)

  end
end

Meanwhile the participations controller handles this:

    class ParticipationsController < ApplicationController
  before_action :authenticate_user!

  def preload
    activity= Activity.find(params[:activity_id])
    participations = activity.participations
    render json: participations
  end

  def create

    if Participation.exists?(user_id: current_user.id)

      redirect_to activities_path(@activity), notice: "Du nimmst bereits teil!"

    else

      @participation = current_user.participations.create(participation_params)
      redirect_to @participation.activity, notice: "Klasse, du nimmst nun teil!"

    end

  end


  def participant
    @participant = user.participations
  end

  def your_matches
    @matches = current_user.participations
  end

  def your_participations
    @activities = current_user.activities
  end

  private

  def participation_params
    params.permit(:activity_id, :status)
  end
end

In my view, I called the controller by using:

<div class="row">
  <div class="col-md-12">
    <h3>Wer kommt bis jetzt mit? </h3>


    <table>
      <tr>
        <th></th>
      </tr>

      <% @participant.each do |participant| %>

          <tr>
            <td><%= participant.user.fullname %></td>
          </tr>

      <% end %>

    </table>

  </div>
</div>

Which gives me a list of all users that participated for any activity. But the only thing I want now is to show all the users which participated for the activity requested. I would say that my relations should work properly, therefore I guess I just need a small hint to solve the problem. At another point of my app I already got a list, where I am able to show the users which participated, but because of the different controllers, I am not able to call this from the activity controller. All in all, this causes an error because I am not able to call the participations_controller from an activitities_view.

<div class="panel-body">
    <% @activities.each do |activity| %>
      <% activity.participations.each do |participation| %>


      <div class="row">

        <div class="col-md-3">
          <%= link_to user_path(participation.user) do %>
              <%= participation.user.fullname %>
          <% end %>
      </div>

Would really appreciate any help and thanks in advance!

dimanche 11 juin 2017

Subscription class not found 'MyChannel' in ActionCable

I am facing a problem while working with Action Cable, whenever I run my program I receive an error that says 'Subscription Class not found 'ConversationChannel'

and when I try to send a message I get this log

    Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
Subscription class not found: "ConversationChannel"
Could not execute command from {"command"=>"message", "identifier"=>"{\"channel\":\"ConversationChannel\"}", "data"=>"{\"message\":[{\"name\":\"conversation_id\",\"value\":\"2\"},{\"name\":\"amitian_id\",\"value\":\"1\"},{\"name\":\"body\",\"value\":\"nmm\"}],\"action\":\"speak\"}"}) [RuntimeError - Unable to find subscription with identifier: {"channel":"ConversationChannel"}]: C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.1/lib/action_cable/connection/subscriptions.rb:74:in `find' | C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.1/lib/action_cable/connection/subscriptions.rb:53:in `perform_action' | C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.1/lib/action_cable/connection/subscriptions.rb:17:in `execute_command' | C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.1/lib/action_cable/connection/base.rb:88:in `dispatch_websocket_message' | C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.1/lib/action_cable/server/worker.rb:58:in `block in invoke'

I will give my channel.rb and other js files

Here is my ConversationChannel.rb

       class ConversationChannel < ApplicationCable::Channel
      def subscribed
        # stream_from "some_channel"
        stream_from "conversations-#{current_amitian.id}"
      end

      def unsubscribed
        # Any cleanup needed when channel is unsubscribed
        stop_all_streams
      end

      def speak(data)

        message_params = data['message'].each_with_object({}) do |el, hash|
          hash[el.values.first] = el.values.last
        end

        ActionCable.server.broadcast(
          "conversations-#{current_amitian.id}",
          message: message_params
        )
      end

     end

Here is my conversation.js

    App.conversation = App.cable.subscriptions.create("ConversationChannel", {
  connected: function() {

  },
  disconnected: function() {

  },
  received: function(data) {
  console.log(data['message']);
  },
  speak: function(message) {
    return this.perform('speak' , {
    message: message
    });
  }
});

$(document).on('submit', '.new_message', function(e) {
  e.preventDefault();
  var values = $(this).serializeArray();
  App.conversation.speak(values);
  $(this).trigger('reset');
});

This is my connection.rb

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_amitian

    def connect
        self.current_amitian = find_verified_amitian
    end

    protected

    def find_verified_amitian
        if(current_amitian = env['warden'].amitian)
            current_amitian
        else
            reject_unauthorized_connection
        end
    end
  end
end

using the log file given above can anyone tell me why It can't find my conversation_channel.rb file ?

Thank you

I Want to develop web application that monitors and extract inforamtion from linux servers. How to begin with Ruby or Python

Learning programming on my own, need some guidance on best platform/tool/language and libraries to build application my own application that monitors, sends and pulls out information (i.e. server logs, data from monitoring tools) from multiple linux servers. ideally i want a client program that keeps pushing the data to sever from where i can show on the web interface.

Rails refuse to generate new controller

Hi everyone and thanks for the great work. I have a problem with rails : I created a fresh app nicely running on port 3000. I'm trying to reate a nw controller using "rails generate controller Welcome index" and rails is throwing this :

Ignoring bindex-0.5.0 because its extensions are not built.  Try: gem pristine bindex --version 0.5.0
/usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/spec_set.rb:87:in `block in materialize': Could not find nokogiri-1.8.0 in any of the sources (Bundler::GemNotFound)
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/spec_set.rb:81:in `map!'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/spec_set.rb:81:in `materialize'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/definition.rb:159:in `specs'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/definition.rb:218:in `specs_for'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/definition.rb:207:in `requested_specs'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/runtime.rb:109:in `block in definition_method'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/runtime.rb:21:in `setup'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler.rb:101:in `setup'
        from /usr/lib64/ruby/gems/2.3.0/gems/bundler-1.15.0/lib/bundler/setup.rb:20:in `<top (required)>'
        from /usr/lib64/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        from /usr/lib64/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        from /usr/lib64/ruby/gems/2.3.0/gems/spring-2.0.2/lib/spring/commands.rb:33:in `<module:Spring>'
        from /usr/lib64/ruby/gems/2.3.0/gems/spring-2.0.2/lib/spring/commands.rb:4:in `<top (required)>'
        from /usr/lib64/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        from /usr/lib64/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        from /usr/lib64/ruby/gems/2.3.0/gems/spring-2.0.2/lib/spring/server.rb:9:in `<top (required)>'
        from /usr/lib64/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        from /usr/lib64/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        from /usr/lib64/ruby/gems/2.3.0/gems/spring-2.0.2/lib/spring/client/server.rb:9:in `call'
        from /usr/lib64/ruby/gems/2.3.0/gems/spring-2.0.2/lib/spring/client/command.rb:7:in `call'
        from /usr/lib64/ruby/gems/2.3.0/gems/spring-2.0.2/lib/spring/client.rb:30:in `run'
        from /usr/lib64/ruby/gems/2.3.0/gems/spring-2.0.2/bin/spring:49:in `<main>'

Does someone have an idea of what this could be ? I cannot figure it out and I will appreciate any help. My OS is opensuse tumbleweed.

Thanks.