mardi 31 janvier 2017

Error on unit testing in rails

I got same errors for all functions in test_controller.rb the error was following

ClassTimingsControllerTest#test_should_be_create: ActiveRecord::Fixture::FormatError: ActiveRecord::Fixture::FormatError Error: ClassTimingsControllerTest#test_should_be_create: NoMethodError: undefined method `each' for nil:NilClass

Here my code in test_controller.rb

test 'should be create' do
assert_difference('Faculty.count') do
  post :create, class_timing: { created_by: @class_timing.created_by, school_year: @class_timing.school_year,
                                standard_id: @class_timing.standard_id, period_name: @class_timing.period_name,
                                org_id: @class_timing.org_id, period_no: @class_timing.period_no,
                                from_time: @class_timing.from_time, to_time: @class_timing.to_time,
                                is_break: @class_timing.is_break, updated_by: @class_timing.updated_by }
end
assert_redirected_to faculty_path(assigns(:class_timing))

end Here my yml code in Fixtures

one: class_timing_id: org_id: 1 school_year: 2016 standard_id: 1 period_no: 1 period_name: MyString from_time: 2017-01-12 04:30:00 to_time: 2017-01-12 05:30:00 is_break: 1 created_by: MyString updated_by: MyString

How can I fix the issue.

ruby on rails prepared statement for oracle view/function

I have the following code which executes an oracle view as follows:

def run_query
    connection.exec_query(
      "SELECT * FROM TABLE(FN_REQRESP(#{type_param},
                                      #{search_type_param},
                                      #{tid_param},
                                      #{last_param},
                                      #{key_param},
                                      #{tran_id_param},
                                      #{num_param},
                                      #{start_date_param},
                                      #{end_date_param}))")
end

The output of the above query is as follows:

SELECT * FROM TABLE(FN_REQRESP('ALL',
 'ALL_TRAN',
 '100007',
 '',
 '',
 '',
 '',
 TO_DATE('27-January-2017','dd-MON-yy'),
 TO_DATE('31-January-2017','dd-MON-yy'))) 

The problem is that above query has a SQL injection vulnerability.

So, i tried to add a prepare statement as follows:

 connection.exec_query('SELECT * FROM TABLE(FN_REQRESP(?,?,?,?,?,?,?,?,?))','myquery',[type_param,search_type_param,tid_param,last_param,key_param,tran_id_param,num_param,start_date_param,end_date_param])

I get the following error now:

NoMethodError: undefined method `type' for "'ALL'":String: SELECT * FROM TABLE(FN_REQRESP(?,?,?,?,?,?,?,?,?))

It's the single quotes that messing it up I beleive. Is there a way to overcome this?

How do I query the database after a Postgres exception?

I'm having some trouble handling concurrency issues when inserting into a Postgres database. The model has a uniqueness constraint on an index column, and so does the Postgres table. Sometimes two threads attempt to insert the same record at the same time (this is unavoidable), in which case both pass the model validation, but the second one violates the Postgres validation. So I catch the exception and everything is ok. This is not the problem.

The problem is my method needs to return the object from the database, so I query the db to get the record inserted by the first thread (I can safely assume it's the same as the one in the second thread). However this fails because the transaction is still in an invalid state due to the failed insert.

My question is: how can I avoid the second exception thrown within the rescue block, and/or enable the method to return the record that was inserted by the first thread?

  class Place
      validates :index_column, uniqueness: true, allow_nil: true

    def self.create_and_insert(some_params)
      more_params = additional_params(some_params)
      place = Place.new(some_params, more_params)

      begin
        place.save  # Insert into place table. This initiates a transaction.
      rescue ActiveRecord::RecordNotUnique => e
        # Oops! Another thread beat us to it.
        # The transaction is now in an invalid state.
        place = Place.find_by(index_column: some_params.id) # This throws a new exception
      end

      place

    end
  end

How to bind one input for two params' values?

I have a problem with my nested form Here is it:

  <%= form_for :project, method: :patch do |f| %>

  <%= f.fields_for :todos_attributes do |todo_form| %>

      <p>
        <%= todo_form.text_field :text, placeholder:"Task name..."%>
      </p>

      <p>
        <%= todo_form.collection_select(:project_id, @projects, :id, :title) %>
      </p>
  <% end %>

  <a href="javascript:undefined" class="hideDiv">Cancel</a>
  <%= f.submit %>
<% end %>

Here is my ProjectsController code to update selected project:

  def update

    @project = Project.find(params[:id])
    @project.update(todo_params)

    redirect_to root_path
  end

  def todo_params
    params.require(:project).permit(:id, todos_attributes: [:text, :project_id])
  end

The problem is that I get an error in update method: "Couldn't find Project with 'id'=index" "index" as understand is default value. How can I set it to be equal to the value(:project_id) selected in collection_select in the form? Thank you!

lundi 30 janvier 2017

acts_as_votable gem likes all the posts on page in rails

Lemme explain what I mean, the point is that I am using acts_as_votable gem in my rails app and it works fyn, problem is that I am using ajax and I am using it to like individual posts from my index page . I will explain with the code

This is my @confessions controller instance variable that has all the votes

 @confessions = Confession.where(amitian_id: ids).order('created_at DESC')

Now this is my view that shows all the posts

  -@confessions.each do |c|
  # code  
  c.get_upvotes.size , remote: true
  c.get_downvotes.size, remote: true
  end

Well, up until now I can use 'c' variable to refer to a single post.. but in my ajax script I have something like this

  $('.like').html('<%=  pluralize(@confessions.get_upvotes.size,"Like") %>');
  $('.dislike').html('<%=  pluralize(@confessions.get_downvotes.size,"Dislike") %>');

Now obviously, this will like all the post variable @confessions have.. how can i write a script to make it like the post user clicks on I suppose I have to use this or self keyword but m not sure how.. help plz

Rails best way (or best practices)

Hi I have a model which I don't know how to focus the following issue:

I have been reading the following posts

I have a project where I wan to manage some properties (Assets). I have House, Owner, Company and Users.

The House and the Owner are linked in the DB with a FK so 1 Company has N Owners and 1 Company has N Houses

The model User is linked to Company, so 1 Company has N users.

How can I access to the company_id in the model Users in order to store this ID in the House and in the Owner model when the House and Owner is created?

  • Do I have to do it in the controller?
  • Do I have to do it in the model?

Thank you

dimanche 29 janvier 2017

How to access Form.select values in rails

I havee this form where I want users to select how they wanna post .. with their name or as anonymous so this is my form for that

- @anonymous.each do |a|
 =form_for @confession , html: {multipart: true} do |f|
    =f.label :Confess
    =f.text_area :confession , require: true
    =f.label :post_as   
     =f.select(:postid,options_for_select([[@confession.amitian.fullname,@confession.amitian.fullname],[a.fullname,a.fullname]]))
    =f.file_field :confessionimage
    =f.submit 'Confess'

Now I have a user with option to select either their name or anonymous to post for that I have to build post with anonymous or current_user m confused how to do that in controller this is what I have done so far

 def index 
 @amitian = Amitian.where(institute: current_amitian.institute) if     amitian_signed_in?
 @confessions = Confession.where(amitian_id: @amitian.ids).order('created_at DESC') if amitian_signed_in?
 @anonymous = Amitian.where(email: 'anonymous@anonymous.com')
 if #params[:postid] == 'Anonymous'  # i need an if statement to check what user has selected .. can anyone help plz ?
 @confession = @anonymous.confessions.build
 else
 @confession = current_amitian.confessions.build 

end

plz I need help with this I need to complete this project soon thanx in advance

Devise::SessionsController (bug?) - Unpermitted parameters

I had the error that appears in Devise Parameter Sanitizer "For" Method Not Found Rails 5

But after reading the solution a new error is appears in the console; I am trying to use simple_form with devise in Ruby 2.3.3p222 and Rails 4.2.3

Log:

Started POST "/users/sign_in" for ::1 at 2017-01-29 19:53:01 +0100
Processing by Devise::SessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"vIcpPg5diOGlDzcwYfEW+SEnY75IQPdCDvcoOzrbNMk4ezv8/f4wkhCLPdFbJ6E4RG19e1+ikif5/GLpQPH0HQ==", "user"=>{"name"=>"Mike", "surname"=>"Nast", "email"=>"mikenast@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
  User Load (1.0ms)  SELECT  `users`.* FROM `users` WHERE `users`.`email` = 'josecr@gmail.com'  ORDER BY `users`.`id` ASC LIMIT 1
Completed 401 Unauthorized in 25ms (ActiveRecord: 1.0ms)
Processing by Devise::SessionsController#new as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"vIcpPg5diOGlDzcwYfEW+SEnY75IQPdCDvcoOzrbNMk4ezv8/f4wkhCLPdFbJ6E4RG19e1+ikif5/GLpQPH0HQ==", "user"=>{"name"=>"Mike", "surname"=>"Nast", "email"=>"mikenast@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
Unpermitted parameters: name, surname, password_confirmation

Also in my controller I have the:

      class Users::RegistrationsController < Devise::RegistrationsController


   prepend_before_action :require_no_authentication, only: [:new, :create, :cancel]
          prepend_before_action :authenticate_scope!, only: [:edit, :update, :destroy]
          prepend_before_action :set_minimum_password_length, only: [:new, :edit]

          before_action :configure_permitted_parameters, if: :devise_controller?

            def configure_permitted_parameters

              devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :surname, :password_confirmation])

            end

In the sign_up view I have the following one:

<%= simple_form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>
              <p><br/>

     <%= f.error_notification %>

        <div class="wrapper wrapper-content  animated fadeInRight">
          <div class="row">
            <div class="col-sm-8">
              <div class="ibox">
                <div class="ibox-content">

                  <div class="form-inputs">
                    <%= f.input :name, :label => 'First Name', required: true, autofocus: true %>
                    <br>
                    <%= f.input :surname, :label => 'Last Name', required: true, autofocus: true %>
                    <br>
                    <%= f.input :email, :label => 'Email', required: true, autofocus: true %>
                    <br>
                    <%= f.input :password, :label => 'Password', required: true %>
                    <br>
                    <%= f.input :password_confirmation, :label => 'Confirm Password', required: true %>
                    <br>
                  </div>

                  <div class="form-actions">
                    <%= f.button :submit, "Sign up" %>
                  </div>
                  <% end %>

Is there anything I missed or did wrong?

Change View based on Option selected in select_tag in rails

I am trying to make a form where a user can wither post normally with their username like this - > normal

  =form_for @confession , html: {multipart: true} do |f|
 =f.label :Confess
 =f.text_area :confession , require: true
 =f.file_field :confessionimage
 =f.select (:id,options_for_select(ID))
 =f.submit 'Confess'

or Anonymously where their Names will be hidden and no one will know that who posted this post .. for this what I thought was I will make a user named anonymous in database and if a user select anonymous in select_form while posting they will post as an anonymous user.

for this in my controller I want something like this and main point that I can't understand is how can the controller know what user has selected ?

this is my controller

    def index 
 @amitian = Amitian.where(institute: current_amitian.institute) if                 amitian_signed_in?
 @confessions = Confession.where(amitian_id: @amitian.ids).order('created_at   DESC') if amitian_signed_in?
  @confession = current_amitian.confessions.build 
  @anonymous = Amitian.where(email: anonymous@anonymous.com)
  # (if anonymous selected )
do @anonymous.confessions.build   
 end

can anyone plz help me how can I achieve this ? Plz hhelp m stuck at this part

devise_token_auth credentials are expiring prematurely

I am using devise_token_auth for user authentication. My client credentials are expiring prematurely(like 3,5 minutes) and i couldn't find the heck why it is so.

Devise config files

initializers/devise_token_auth.rb

DeviseTokenAuth.setup do |config|
  config.change_headers_on_each_request = true         
  config.token_lifespan = 24.hours      
  config.default_confirm_success_url = "http://localhost:4000"
end

initializers/devise.rb

Devise.setup do |config|
  config.mailer_sender = "support@theinnerhour.com"
  config.navigational_formats = [:json]

end

models/user.rb

class User < ActiveRecord::Base     
    devise :database_authenticatable, :registerable,
    :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:google_oauth2,:facebook] 
    include DeviseTokenAuth::Concerns::User
end

I confirmed expiry header set to after 24 hours after authenticating the user, but still they expire after 3-5 minutes and subsequent api calls give invalid credentials error.

Thanks

Is there any difference between aggregate([{:$project => {:_id=>1}}]) and projection({:_id=>1}) in mongodb?

Both of the two expressions below in mongodb return the same value:

db.collection.find().aggregate([{:$project => {:_id=>1}}])

db.collection.find().projection({:_id=>1})

While I just wondering is there any difference between them?

page layout on prawn unable to set inside class

i have searched in prawn about page layout in prawn and it showed this

pdf = Prawn::Document.new(:page_size => "A4", :page_layout => :landscape)

pdf.text doesnt print anything

but when i try this i'm getting undefined method

page_layout :landscape

added after super()

this is my whole code

class ProductPdfGenerate < Prawn::Document
    require 'open-uri'
    def initialize(order_items)
        super()
        @document = Prawn::Document.new(:page_size => "A4", :page_layout => :landscape)
        @order_items = order_items
        @order_items.each_with_index do |oi, i|
            if oi.case.present? && Model.where(magento_model_id: oi.case.model_id).first.present?
                style_image = oi.case.image_preview.url(:custom_image)
                model = Model.where(magento_model_id: oi.case.model_id).first
                # image open(style_image), width: "200".to_f, height: "400".to_f
                image open(style_image), width: "#{model.aspect_ratio_width.to_f/2.54*72}".to_f, height: "#{model.aspect_ratio_height.to_f/2.54*72}".to_f
                text "\n \n \n"
                text "Model: #{model.name}"
                text "Model Category: #{model.category_type}"
                text "Style: #{oi.case.style.try(:name)} "
                text "Order Id: #{oi.order_id}"
            else
                image open("http://ift.tt/2kg54Ti")
            end
        end
    end
end

samedi 28 janvier 2017

Rails mina deploy install nginx as module

I'm trying to instal nginx as a module with mina deploy but i get,

expecting keyword_end

...nf-path=/etc/nginx/nginx.conf --pid-path=/var/run/nginx.pid ..

.

on modules setup.

the setup that i'm trying to instal is:

 desc "install Nginx"
    task :install do
        invoke :sudo
        queue "passenger-install-nginx-module --auto  --languages ruby,python,nodejs,meteor --nginx-source-dir=/home/ubuntu/nginx-1.9.14 --prefix=/usr --extra-configure-flags="--conf-path=/etc/nginx/nginx.conf --pid-path=/var/run/nginx.pid --sbin-path=/usr/sbin --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --with-pcre='/home/ubuntu/nginxmodule/pcre-8.37'  --with-http_gzip_static_module  --with-http_stub_status_module --without-mail_pop3_module --without-mail_smtp_module --without-mail_imap_module --with-http_gzip_static_module --without-http_autoindex_module --without-http_browser_module --without-http_fastcgi_module --without-http_geo_module --without-http_empty_gif_module --without-http_map_module --without-http_ssi_module --without-http_userid_module --user=www-data --group=www-data  --with-http_ssl_module  --add-module='/home/ubuntu/nginxmodule/openssl-1.0.1s' --add-module='/home/ubuntu/nginxmodule/nginx-rtmp-module' --add-module='/home/ubuntu/nginxmodule/headers-more-nginx-module-0.26' --add-module='/home/ubuntu/nginxmodule/ngx_pagespeed-release-1.11.33.0-beta' --add-module='/home/ubuntu/nginxmodule/nginx-push-stream-module' --add-module='/home/ubuntu/nginxmodule/ngx_http_redis-0.3.8'""
    end

someone have a idea how to setup a nginx module inside mina-deploy? thank's

Why i am getting error "plan not exist " in my rubyonrails website?(link is given below)

[every time i click on sign up in both basic and pro membership page i get this error][1] Below is my whole project.please help as i cannot send my app to heroku without get this to work

how to create guest user to angular rails app without populate database?

I have angular - rails web application. My web app is already in production mode.i'm using devise gem. I want to create a demo for Guest Users to login as admin or regular users to try it.
How i make guset users use all features of my application without populate my original database ?
How i distinguish admin guset users from regular guest users?

vendredi 27 janvier 2017

Rails: how to submit multiple forms to the same table

I am currently building a tool for work. It involves submitting multiple job start and end times every day. There are several jobs and each one has a new run time every day. So to speed up the process I want to submit all of the run times in one form. Currently I have all of the forms appearing but when I submit only one submission goes through. What am I missing?

runtime.rb

class Runtime < ApplicationRecord
  belongs_to :Mrpjob
  accepts_nested_attributes_for :Mrpjob
end

runtimes_controller.rb

class RuntimesController < ApplicationController
  before_action :set_runtime, only: [:show, :edit, :update, :destroy]

  # GET /runtimes
  # GET /runtimes.json
  def index
    @runtimes = Runtime.all
    @sorting = @runtimes.order("date asc")
  end

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

  # GET /runtimes/new
  def new
    @runtime = Runtime.new
    @mrpjobs = Mrpjob.all
    @runtimes = Array.new(Mrpjob.count)
  end

  # GET /runtimes/1/edit
  def edit
    @mrpjobs = Mrpjob.all
  end

  # POST /runtimes
  # POST /runtimes.json
  def create
    @runtime = Runtime.new(runtime_params)


    respond_to do |format|
      if @runtime.save
        format.html { redirect_to @runtime, notice: 'Runtime was successfully created.' }
        format.json { render :show, status: :created, location: @runtime }
      else
        format.html { render :new }
        format.json { render json: @runtime.errors, status: :unprocessable_entity }
      end
    end
  end

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

  # DELETE /runtimes/1
  # DELETE /runtimes/1.json
  def destroy
    @runtime.destroy
    respond_to do |format|
      format.html { redirect_to runtimes_url, notice: 'Runtime was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def runtime_params
      params.require(:runtime).permit(:start_time, :end_time, :date, :Mrpjob_id)
    end
end

_form.html.erb

<%= form_for @runtime, :html => { :class => "form-horizontal runtime" } do |f| %>

  <% if @runtime.errors.any? %>
    <div id="error_expl" class="panel panel-danger">
      <div class="panel-heading">
        <h3 class="panel-title"><%= pluralize(@runtime.errors.count, "error") %> prohibited this runtime from being saved:</h3>
      </div>
      <div class="panel-body">
        <ul>
        <% @runtime.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
        </ul>
      </div>
    </div>
  <% end %>
  <div class="col-sm-6 padding">

    <div class="form-group">
      <%= f.label :start_time, :class => 'control-label col-lg-2' %>
      <div class="col-lg-6">
        <%= f.text_field :start_time, :class => 'form-control' %>
      </div>
      <%=f.error_span(:start_time) %>
    </div>
    <div class="form-group">
      <%= f.label :end_time, :class => 'control-label col-lg-2' %>
      <div class="col-lg-6">
        <%= f.text_field :end_time, :class => 'form-control' %>
      </div>
      <%=f.error_span(:end_time) %>
    </div>
    <div class="form-group">
      <%= f.label :date, :class => 'control-label col-lg-2' %>
      <div class="col-lg-6">
        <%= f.text_field :date, :class => 'form-control' %>
      </div>
      <%=f.error_span(:date) %>
    </div>

     <div class="row">
        <% @mrpjobs.each do |p| %>
          <div class="col-sm-2 text-center">
            <%= f.radio_button :Mrpjob_id, p.id %>
            <%= f.label :Mrpjob_id, p.name %>
          </div>
        <% end %>
    </div>

    <div class="form-group">
      <div class="col-lg-offset-2 col-lg-10">
        <%= f.submit nil, :class => 'btn btn-primary' %>
        <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
                  runtimes_path, :class => 'btn btn-default' %>
      </div>
    </div>
  </div>

<% end %>

new.html.erb

<%- model_class = Runtime -%>
  <div class="page-header">
    <h1><%=t '.title', :default => [:'helpers.titles.new', 'New %{model}'], :model => model_class.model_name.human.titleize %></h1>
  </div>

  <div class="container">
    <div class="row">

        <% @runtimes.each do |runtime| %>
            <%= fields_for @runtime do |r| %>
              <%= render "form" %>
            <% end %>
        <% end %>
    </div>
  </div>

Get only the query string in current view

I am setting the canonical URL for my Rails site which has many many subdomains that render the exact same content as the main domain.

I am adding this to the top of my layouts:

<link rel="canonical" href="http://ift.tt/2kuDMFL}" />

Which makes sure Google crawlers know the definitive source to help my SEO.

The above code does not include the query string when one exists

I can request.query_parameters and then break that out into a string... but is there an easy way to just get the ?provider=233 query string out of requests?

Rake spree_sample:load error

After cloning ShopSpree Sales, I followed the installation instructions - db create, migrate, and almost worked fine except bundle exec rake spree_sample:load. It gives the following error :

asdf08:~/workspace (master) $ bundle exec rake spree_sample:load
Loaded Payment Methods samples
Loaded Shipping Categories samples
Loaded Shipping Methods samples
Loaded Tax Categories samples
Loaded Tax Rates samples
rake aborted!
Chewy::UndefinedUpdateStrategy: Index update strategy is undefined in current context.
Please wrap your code with `Chewy.strategy(:strategy_name) block.`
/usr/local/rvm/gems/ruby-2.3.0/gems/chewy-0.8.3/lib/chewy/strategy/base.rb:17:in `update'
/usr/local/rvm/gems/ruby-2.3.0/gems/chewy-0.8.3/lib/chewy/type/observe.rb:70:in `update_index'
/usr/local/rvm/gems/ruby-2.3.0/gems/chewy-0.8.3/lib/chewy/type/observe.rb:28:in `block in update_proc'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:446:in `instance_exec'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:446:in `block in make_lambda'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:263:in `block in simple'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:506:in `block in call'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:506:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:506:in `call'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:92:in `__run_callbacks__'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:778:in `_run_commit_callbacks'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.4/lib/active_record/transactions.rb:314:in `committed!'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.4/lib/active_record/connection_adapters/abstract/transaction.rb:89:in `commit_records'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.4/lib/active_record/connection_adapters/abstract/transaction.rb:153:in `commit'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.4/lib/active_record/connection_adapters/abstract/transaction.rb:175:in `commit_transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.4/lib/active_record/connection_adapters/abstract/transaction.rb:194:in `within_new_transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.4/lib/active_record/connection_adapters/abstract/database_statements.rb:213:in `transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.4/lib/active_record/transactions.rb:220:in `transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.4/lib/active_record/transactions.rb:348:in `with_transaction_returning_status'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.4/lib/active_record/transactions.rb:291:in `save!'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.4/lib/active_record/persistence.rb:51:in `create!'
/usr/local/rvm/gems/ruby-2.3.0/bundler/gems/spree-a275c9db4f0c/sample/db/samples/products.rb:129:in `block in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/bundler/gems/spree-a275c9db4f0c/sample/db/samples/products.rb:124:in `each'
/usr/local/rvm/gems/ruby-2.3.0/bundler/gems/spree-a275c9db4f0c/sample/db/samples/products.rb:124:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/polyglot-0.3.5/lib/polyglot.rb:65:in `require'
/usr/local/rvm/gems/ruby-2.3.0/gems/polyglot-0.3.5/lib/polyglot.rb:65:in `require'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:274:in `block in require'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:240:in `load_dependency'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:274:in `require'
/usr/local/rvm/gems/ruby-2.3.0/bundler/gems/spree-a275c9db4f0c/sample/lib/spree/sample.rb:13:in `load_sample'
/usr/local/rvm/gems/ruby-2.3.0/bundler/gems/spree-a275c9db4f0c/sample/lib/spree_sample.rb:16:in `load_samples'
/usr/local/rvm/gems/ruby-2.3.0/bundler/gems/spree-a275c9db4f0c/sample/lib/tasks/sample.rake:20:in `block (2 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/cli/exec.rb:74:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/cli/exec.rb:74:in `kernel_load'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/cli/exec.rb:27:in `run'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/cli.rb:332:in `exec'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/vendor/thor/lib/thor.rb:359:in `dispatch'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/cli.rb:20:in `dispatch'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/vendor/thor/lib/thor/base.rb:440:in `start'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/cli.rb:11:in `start'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/exe/bundle:34:in `block in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/lib/bundler/friendly_errors.rb:100:in `with_friendly_errors'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.13.6/exe/bundle:26:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/bin/bundle:23:in `load'
/usr/local/rvm/gems/ruby-2.3.0/bin/bundle:23:in `<main>'
/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 `<main>'
Tasks: TOP => spree_sample:load

The core error seems to be -

Chewy::UndefinedUpdateStrategy: Index update strategy is undefined in current context.

Can anyone point the direction of solution ?

Rails destroy js.erb

Can you tell me please, how I could remove object before destroy method will be end. When I use next pattern, removing object happen when photo was delete, but it take 1 or 3 or more seconds. _form(edit action) <% listing.photos.each do |photo|%> <%= image_tag photo.image.thumb, class: 'thumbnail', id: "test"%> <%= link_to "remove", photo_path(photo),class: 'btn btn-primary', method: :delete, data: { confirm: 'Are you sure?' }, remote: true %>

destroy.js.erb

$('#test').remove();

How I can use this pattern

_form:

<div id="test_<%= photo.id %>"> <%= image_tag photo.image.thumb, class: 'thumbnail'%> <%= link_to "remove", photo_path(photo),class: 'btn btn-primary', method: :delete, data: { confirm: 'Are you sure?' }, remote: true %>

Destroy.js.erb:

 $('#edit_image_<%= @photo.id %>').remove();

Ruby rmagick: How to make text more bold?

def change_image_labels(feed_data)
 for data in feed_data
  img = Image::read(@tmpdir_file_path+"/#{data[0]}.png").first.resize(600,600)
 redback = Image::read("#{Rails.root}/tmp/redback.png")[0]
 txt = Magick::Draw.new
 redback.annotate(txt,0,0,0,0,data[2]){
   txt.gravity = Magick::WestGravity
   txt.pointsize = 50
   txt.fill = "#ffffff"
   txt.font_family = 'helvetica'
   txt.font_weight = Magick::BoldWeight
 }
 img = img.composite(redback, 0, 30, AtopCompositeOp)
 img.write(@tmpdir_file_path+"/#{data[0]}.png")
end
end

Here I am trying to annotate an image with reb background with a text.

Here `redback.annotate(txt,0,0,0,0,data[2]` `data[2]` refers to the text which contains data like 92% OFF. I want to make it bold.

Please refer to below images-

Actual Result-

enter image description here

Desired Result (Boldness)-

enter image description here

As you can the second image contains a text which is more bold.

Please help.

jeudi 26 janvier 2017

Update database column in rails

I have a problem, I want to update my database's "active" column. my schema =

 tablename(name:string , id:int , active:0 ,created_at)

I want to update active attribute in my rails app after a certain period of time let say 2 days from the created_at time

I have tried few stuff like this from controller but none of this worked for me.. can anyone help ?

def check_aim
@aim = Aim.find(1)

aimdays = @aim.day
futuredate = @aim.created_at+aimdays.days
 if(Time.now == futuredate)
 @aim.active = 0;  // i have tried @aim.update_attribute(:active,1) also didn't word either
 @aim.save
end
 if @aim.save
saved
else
not saved  
end
end
helper_method :check_aim

view class

=debug check_aim

this returns

saved

but when i see my database nothing has changed ... plz help

how to check condition in rspec. is ignored the condition

how to check condition in rspec. The problem is that is ignored the condition.how to check condition in rspec. The problem is that is ignored the condition.

Have test. I check helper_method :gta_data

if @dynamic_page
  gaPageUid = 'category-' + @dynamic_page.uid
elsif @product
  gaPageUid = 'product'
else
  gaPageUid = 'other'
end

describe '#gtm_data' do
  before :each do
    I18n.region = "de"
    I18n.language = "de"
    I18n.locale = "de"
  end

  context "when dynamic page" do
    let!(:object) {
      FactoryGirl.create(:dynamic_page_published,
                         og_title: translation_for(:de),
                         og_site_name: translation_for(:de),
                         og_description: translation_for(:de),
                         slug: "/with-og-attributes")
    }
    it do
      expect(subject.gtm_data).to eq({gaLocale: 'de', gaLanguage: 'de', gaRegion: 'de',
                                      gaPageUid: 'category-' + object.uid})
    end

  end
end

I get the following message.

   expected: {:gaLocale=>"de", :gaLanguage=>"de", :gaRegion=>"de", :gaPageUid=>"category-misc-1"}
   got: {:gaLocale=>nil, :gaLanguage=>nil, :gaRegion=>"de", :gaPageUid=>"other"}

Is there a way to make this code DRY?

I have a Command and Server model which are associated with has_many_and_belongs_to in both model.

I also have commands_servers table which store command_id and server_id.

I have added the commands in the Command table and also server.commands.push(commands) will automatically populate the commands_servers table.

    ["123","456abc", "987jhg"].each do |partnum|
      command = "workworkwork"
      commands = Command.create( name: "command1", partnum: partnum, command: command)      
      ["server1", "server2"].each do |assettag|
        server = Server.find_by_assettag(assettag)
        server.commands.push(commands) 
      end
      command = "playplayplay"
      commands = Command.create( name: "command2", partnum: partnum, command: command)
      ["server3", "server4", "server5"].each do |assettag|
        server = Server.find_by_assettag(assettag)
        server.commands.push(commands)  
      end
    end

So, I was wondering can i refactor the code to make it DRY because i think i am repeating.

method for determining data for google tracking manager

I have a method for defining data for google tracking manager. First logic organized in views, but I think this is not right. Tell, make a method in the controller(application_controller) or in the model?

def gtm_data(data_hash = nil)
  @gtm_data ||= {}

  if @dynamic_page
    gaPageUid = 'category-' + @dynamic_page.uid
  elsif @product
    gaPageUid = 'product'
  else
    gaPageUid = 'other'
  end

  @gtm_data = {
   gaLocale: @locale, gaLanguage: @lang,
    gaRegion: current_site.region, gaPageUid: gaPageUid
  }

  # setter call
  @gtm_data.merge!(data_hash) if data_hash

  @gtm_data
end

mercredi 25 janvier 2017

link_to popup modal div not working in rails

I am making a rails app where I want to show a modal popup div whenever I click on link_to 'Add new Progress' I tried to do it but didn't work out well. Javascript gives no errors I don't know what to do. please help anyone

my code = View file

.modal.fade#myModal
.mymodal-content
    My content goes here
#main_div_index.row.clearfix

    #index_sidebar_aims
        %h4=link_to 'I have a new AIM' ,{'class':'opener','data-toggle':"modal" ,'data-target':"#myModal"}
        %br
        %h4=link_to 'I made progress' , aims_path
#index_progress_div.col-md-6.col-xs-6.col-sm-6
    show feeds from : 

my code = javascript

var open = $('.opener');
var modal = $('.mymodal');

 open.onclick = function(){
    modal.style.display='show';
 }

my code css

.mymodal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

 /* Modal Content */
 .mymodal-content {
  position: relative;
  background-color: #fefefe; }

How to render a layout on button click in rails?

How may I make a tabular layout that render different layouts in rails just like github [How may I make a tabular layout that render different layouts in rails just like github

I want to do something similar to this in my application

I have my own button with drop down and I want to render layout according to the user's selection [ I have my own button with drop down and I want to render layout according to the user's selection2

please help !!

Render a layout on button click in rails

This is my drop down button

I am using Rails to render a layout depending on what user has selected from this dropdown menu and I have no idea how may I render a layout from within link_to

eg:
 #main_div
    show feeds from : 
        %button.dropbtn{'onclick':'myfunc()'}
            Dropdown
            %span.caret
        #myDropdown.dropdown-content
            =link_to 'public'
            =link_to 'followers'
    =render 'progress'

in this the way I am rendering progress statically I want to render it on button click something like this :

  =link_to 'public' , render: 'progress'

One more problem is that even if this works I want layout to be rendered in another div (main div as of snippet ) not in link_to's div as you can see in code

Ruby on Rails: How to validate if on specific page?

In my Ruby on Rails application I am trying to add in validations that will ensure the user has entered a value in a text box. In my system I have a table called Account which stores users' email account information, when they go onto the views/accounts/_form.html.erb page to add a new email account I want to validate the presence of a port number. I can do this through the following code:

validates :port, presence: true

This successfully ensures that users enter their port number, but when a user signs up through the views/users/_new.html.erb page they have to enter only an email address (e.g example@example.com) and the users_controller will then create a record in the Account table for this email address. My problem is that on the views/accounts/_form.html.erb page the port number is required but on the views/users/_new.html.erb it is not.

Is there a way of validating that the user enters the port number if they are on the views/accounts/_form.html.erb page or invoking the create method in the accounts_controller?

I am aware that I could do this through the HTML required validation like so: <%= f.text_field :port, :required => true %> but I need to add in further validation as well as presence, so this is not suitable.

how to access class method from instance method

I have model:

class UserWeight < ActiveRecord::Base

  self.table_name = 'Weight'

  scope :logged_between, lambda { |start_date, end_date|
    where(weight_date: start_date.to_date...(end_date.to_date.end_of_day)) unless
    start_date.nil? || end_date.nil?
  }

  # returns the sum of points 
  def total_points
      self.class.Userweight
    (UserWeight.blank?) ? 0 : UserWeight.inject(0) {|a, e| a + e.points}
  end
end

Active record is returning collection of arrays. I want to access class method and do the sum in the instance method. Any idea how can i do that?

Thanks

Rails 4.1 undefined method `usual_start_time' for nil:NilClass

I have a form which creates the default time of 6.45pm. When a new form is created

_form.html.erb

 = f.input :started_at, as: :string, class: 'form-control', input_html: { value: l(@happening.started_at, format: :date_time_picker), class: 'date_time_picker' }, label: "Start at"

but instead of showing 1845 in my happenings controller i want to replace it with the usual_start_time field in my areas table

scheme.rb

create_table "areas", force: :cascade do |t|
    t.string  "deprecated__default_postcode", limit: 255
    t.integer "number_of_runners_needed",                 default: 100,     null: false
    t.string  "referral_partners_logo_image"
    t.integer "address_id"
    **t.string  "usual_start_time",                         default: "18:45"**
  end

I have tried using

time = DateTime.strptime((Date.today + 1.day).to_s + ' ' + **"#{@area.usual_start_time}"**, '%Y-%m-%d %H:%M')

but it gives me undefined method `usual_start_time' for nil:NilClass

also tried

time = DateTime.strptime((Date.today + 1.day).to_s + ' ' + **"#{@area.happenings.usual_start_time}"**, '%Y-%m-%d %H:%M')

happenings_controller.rb (want to replace "18.45"

  def new
    @type = params[:type].underscore
    time = DateTime.strptime((Date.today + 1.day).to_s + ' ' + **"18:45"**, '%Y-%m-%d %H:%M')
    @happening = Happening.new(started_at: time)
  end

mardi 24 janvier 2017

Redis_analytics when deployed on Heroku?

How do I connect to redis-server for redis_analytics gem on heroku? Locally I ran redis-server on a new terminal which solves my issue but how do I do one on heroku?

NoMethodError (undefined method `incr' for nil:NilClass):

vendor/bundle/ruby/2.3.0/gems/redis_analytics-1.0.1/lib/redis_analytics/visit.rb:81:in `counter'

vendor/bundle/ruby/2.3.0/gems/redis_analytics-1.0.1/lib/redis_analytics/visit.rb:49:in `record'

Config/initializers/redis.rb:

$redis = Redis.new(url: ENV["REDIS_URL"])

Ruby on Rails - Separate Edit Pages

I'm currently trying to add a privacy page to allow my users to modify their privacy settings. I'm using rails-settings to store those settings but creating a layout and updating them is causing me issues.

I created a new page privacy.html.erb, and have it rendering a new partial _privacy.html_erb. The problem is that I cannot simply map the values as if they were just columns.

As in, I can't do <%= f.text_field :name %> as the settings structure is different.

// user.rb has settings stored in this manner.

has_settings do |s|
    s.key :global, :defaults => { :visibility => PRIVACY_ANYONE }
end

Which can be easily gotten through this call.

return settings(:global).visibility
> returns PRIVACY_ANYONE 

So, instead of using form_for, I could instead use form_tag and manually add each field and values. But that sounds like a hacky solution.

And how do I go about saving/updating these values?

Within routes, I've added two routes to get the edit page, and have a post, which does call the correct UserController methods, but the post seems to clear the user so I can't do anything.

// routes.rb

resources :users do
    get 'privacy'
    post 'privacy' => 'users#privacysave'
end

  • What would be the best way to handle this case?
  • Should I move away from rails-settings and just add another table?
  • And how do I update those values?

Append ruby partial in javascript, and pass a rails variable

Creating a chat component with ActionCable in Rails5. I learned today that render partial, even in .js.erb does not work. render specifically is the issue. So now I'm trying to call a partial, and pass a ruby variable to it.

I have tried many things, currently this is how I'm trying to accomplish it:

chatbox.append(<%= j (Erubis::Eruby.new(File.read(File.join(Rails.root, 'app/views/msgs',
        '_msg.html.erb'))).result(msg: @msg)) %>);

and the error is

 undefined method `self_or_other' for #<Erubis::Eruby:0x007f832bbb8590>

So the partial is there, but the variable is not correct.


views/msgs/_msg.html.erb

<li class="<%=  self_or_other(msg) %>">
  <div class="avatar">
    <%# if msg_interlocutor(msg).avatar.url(:thumb) == "thumb/missing.png" %>
    <%= image_tag(msg_interlocutor(msg).avatar.url(:thumb), class: "convoPic")%>
</div>
</li>

I also tried:

chatbox.append(<%= j (Msg.new(File.read(File.join(Rails.root, 'app/views/msgs',
        '_msg.html.erb'))).result(msg: @msg)) %>);

And get this error: When assigning attributes, you must pass a hash as an argument.

How do I properly call in a partial, pass it a ruby variable (with the msg record). Thank you!!

How to query from rails console?

In rails console

Item.last 

gives me this result.

=> #<Item id: 1484767245888254, 
            partnum: ["xyz", "abc", "efg"], 
            display_port: nil, 
            able_id: 1484767244590695, 
            able_type: "money">

Suppose to query the record with

able_type = "money" 

we can do

Item.where(able_type: "money")

But, How to query the above result if i know the partnum which is "xyz" (there is a array of string in partnum).

Rails Validate has_many Through on a wicked wizard form

I'm trying to validate a product form with has many through colors and sizes on a multi-step wicked wizard form using this gem enter link description here

but did not validate the step, someone have any idea how to validate related models on a wizard form? thank's

i've trying to validate through color model. but in this case scenario seems that is just possible through the product model.

class Product < ActiveRecord::Base

 has_many :sizeships
  has_many :sizes, through: :sizeships
  has_many :colorships
  has_many :colors, through: :colorships


 include Wicked::Wizard::Validations

    def self.wizard_steps
        [
            "first"
          ]
    end
end





class Color < ActiveRecord::Base
  attr_accessible :name, :hex


  has_many :colorships
  has_one :colorship
  has_many :products, :through => :colorships

  accepts_nested_attributes_for :products, :order

  include Wicked::Wizard::Validations

  def current_step
    product.current_step 
  end


  def wizard_steps
    Product.wizard_steps
  end

  def color_id_validations
    {

      color_id: {
        presence: {
          presence: true      }
      }
    }
  end

end

Is a bad pratice to use long method name in ruby/rails?

I have the following service class in ruby:

class EnableUserMatriculations

  def initialize(user)
    @user = user
  end

  def call!
    matriculations_that_current_user_is_matriculated_and_confirmed.each do |matriculation|
      matriculation.enable!
    end
  end


  private

  def matriculations_that_current_user_is_matriculated_and_confirmed
    # some logic to search user.matriculations that must be enabled
  end
end

And I would like to know if methods with long names is a bad pratice?

I dont like to use comments.

Please, give me opinions about this.

Thanks in advance

How to Kill threads that are present in Controller in its model (Ruby 2.1.2 on Rails 3.2.13)

I have a controller RamsController in that I have this method

def check_status
   @ram = Ram.find(params[:id])
   if @ram.workflow == "start"
      thread_check_status = Thread.new do
         thread.current[:name] = "thread_manual_traige"
         @ram.check_status!
         ActiveRecord::Base.connection.close
      end
      @ram.thread_check_status = thread_check_status
   end
  render json: { status: "success" }
end

I have a model code like this

class Ram < ActiveRecord::Base

attr_accessor :thread_check_status 

  def self.kill_threads
    self.thread_check_status.kill
  end

  def exception_handler(exception)
   if exception == "exited by user"
     self.kill_threads
   end
  end

Whenever an exception is caught it will go to the exception_handler method in the model. And now, I'm trying to kill the thread when the exception is caught so I tried to assign the thread to the variable @ram.thread_check_status = thread_check_status So I created a method def self.kill_threads in the model to kill the threads and called that method in def excpetion_handle method.

But, it is not working I think I assigned the thread to the variable in a wrong way @ram.thread_check_status = thread_check_status

Please suggest me how to kill the threads associated with @ram id in the model.

And I have two more methods in RamsController with two more threads and I'm trying kill those threads too.

Ruby on Rails: Display confirmation message if not includes

In Ruby on Rails, is it possible to display a confirmation message if the user has not entered a string in a text field? I have a form whereby a user enters text in a text field and want to show a confirmation message if they do not enter a certain string. A simple example could be a text field where users can enter items they want to buy from the shop, such as "bread, potatoes, eggs", and so a confirmation message would appear when they click submit saying "You have not entered milk, are you sure you want to proceed?".

I am have the below code working when a user clicks "destroy", and so wonder if this can be developed to work when a user clicks "submit"?

 <%= link_to 'Destroy', email_path(email), method: :delete, data: { confirm: 'Are you sure?' } %>

Select an object nested attribute in create Active admin

Nested attribute

I have a User that has many book, and a book belongs to a User. I want to create a user from active admin and select a book that was already created and it has no user.

User class :

class User < ActiveRecord::Base
  has_many :books
  accepts_nested_attributes_for :books 
end

Book class :

class Book < ActiveRecord::Base
  belongs_to :user
end

Active Admin User:

ActiveAdmin.register User do
  form do |f|
    f.inputs do
      ...
      f.has_many :books do |referral|
        referral.input :name
      end
      ...
    end
  end
end

I have added a autocomplete that retrieves the names of the books, The problem is if I select one book and this book has no user associated I got an error saying that the book is already taken because it tries to create a new book with the specific name.

lundi 23 janvier 2017

rails Validate has_many through

I'm trying to validate has_many through association using the id or the validade associated method but, the log spits out!

someone have any idea how to validate a has_many through? thank's

syntax error, unexpected '[', expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END if !halted && true && (validation_context == :[:update])

validates :image_id, :size_id, :color_id,  presence: true, :on => [  :update ]

validates_associated :images, :sizes, :colors, presence: true, :on => [  :update ]

Rails 3 to 4 upgrade - Dropbox OAuth API - Missing CSRF Token in session

I recently upgraded a Rails 3 app which used cookies for authentication to Rails 4 and found that the Dropbox API is now giving the following error:

DropboxOAuth2Flow::BadStateError (Missing CSRF token in session.)
... :in `finish_connect'

As I understand it, the CSRF token has been moved to a secure cookie in Rails 4, but I'm unsure of how to tell Dropbox how to deal with it.

How would I change the following code to work with Rails 4?

access_token, user_id, url_state = DropboxOAuth2Flow.new(@APP_KEY, @APP_SECRET, redirectURI, cookies, :dropbox_auth_csrf_token).finish(params)

Ruby on Rails: In controller, retrieve data from text_field based on HTML ID

In my RoR application, I am trying to create a form whereby users can update the fields of multiple records at once. To do this I have been following this RailsCast guide http://ift.tt/29dnsZk but this does fully show me what to do.

The problem I have is that I have a Recipient model and want to update the fields of multiple records at once with different data. For example, in this Recipient model I have the columns contact_id and information and what I want to do is allow a user to update the records with the data for the information column on one form.

My edit_multiple.html.erb form is as follows:

<h1>Recipient Specific Information</h1>
<table>
  <tr>
    <th>Contact</th>
    <th>Information</th>
  </tr>
  <%= form_for :recipient, :url => update_multiple_recipients_path, :html => { :method => :put } do |form| %>
    <% for recipient in @recipients %>
        <tr>
            <%= hidden_field_tag "recipient_ids[]", recipient.id %>
            <td><% if not recipient.contact_id.blank? %><%= recipient.contact.firstname %><% elsif not recipient.group_id.blank? %><%= recipient.group.name %><% end %></td>
            <td><%= form.text_field :information, id: recipient.id %></td>
        </tr>
    <% end %>
    <%= form.submit "Submit" %>
  <% end %>
</table>

Recipients_controller:

class RecipientsController < ApplicationController
    def edit_multiple
        @recipients = Recipient.where(:email_id => params[:id])
    end
    def update_multiple
        @recipients = Recipient.find(params[:recipient_ids])
        @recipients.each do |recipient|
            recipient.update_attributes(recipient_params)
        end
        flash[:notice] = "Updated products!"
        redirect_to root_path
    end
    private
    def recipient_params
      params.require(:recipient).permit(:contact_id, :information)
    end
end

Routes.rb:

resources :recipients do
 collection do
   get :edit_multiple
   put :update_multiple
 end
end

My problem is that the following code on the view displays the recipient's contact name and a text_field for each one recipient so that the user can enter the information they want to store for each recipient. Currently, when it comes to updating the records, what happens is the data entered into the text_field for the information parameter on the record display last is saved for each of the records. What should happen is that the data entered into of text_fields for each of the records should get saved.

My question is whether it is possible to identify each of the text fields on the view via their HTML ids in the controller? This is because I am wondering whether it would then be possible to change the below code in the controller to identify each text field and store the data entered into the corresponding recipient row.

def update_multiple
        @recipients = Recipient.find(params[:recipient_ids])
        @recipients.each do |recipient|
            # is it possible to take the data entered in a specific text field?
            recipient.update_attributes(recipient_params)
        end
        flash[:notice] = "Updated products!"
        redirect_to root_path
    end

dimanche 22 janvier 2017

How can I not authenticate everytime in StackExchange API calls using JS client?

I am using this code from the StackExchange App Documentation to get the user information from StackOverflow.

// For simplicity, we're using jQuery for some things
//   However, the library has no jQuery dependency
$(function(){
// Initialize library
SE.init({ 
    // Parameters obtained by registering an app, these are specific to the SE
    //   documentation site
    clientId: 1, 
    key: 'U4DMV*8nvpm3EOpvf69Rxw((', 
    // Used for cross domain communication, it will be validated
    channelUrl: 'http://ift.tt/1JgVaaL',
    // Called when all initialization is finished
    complete: function(data) { 
        $('#login-button')
            .removeAttr('disabled')
            .text('Run Example With Version '+data.version); 
    }
});

// Attach click handler to login button
$('#login-button').click(function() {

    // Make the authentication call, note that being in an onclick handler
    //   is important; most browsers will hide windows opened without a
    //   'click blessing'
    SE.authenticate({
        success: function(data) { 
            alert(
                'User Authorized with account id = ' + 
                data.networkUsers[0].account_id + ', got access token = ' + 
                data.accessToken
            ); 
        },
        error: function(data) { 
            alert('An error occurred:\n' + data.errorName + '\n' + data.errorMessage); 
        },
        networkUsers: true
    });
});
});

This code works fine but I noticed that everytime it fires and gives the response access_token changes. How I can I just get user information using the access token. Plus this is returning user's data with all the sites he is part of. How can I limit it to just StackOverflow. I am unable to find proper documentation for this.

Can anyone please point me to the JS methods for making API calls from StackExchange API?

Rack::Deflater works if only added to config.ru

Why am I getting Error: incorrect header check when add

config.middleware.use Rack::Deflater

to class Application < Rails::Application. But don't when I add use Rack::Deflater to config.ru? I double checked: gzip works and compresses responses.

samedi 21 janvier 2017

Rails predictor array_to_json

I'm, trying to create a prediction of product using predictor gem and ip_address but rails spits out

no such function: array_agg

someone have any idea what this array_agg mean? thank's

gem link http://ift.tt/KeiJUV

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such function: array_agg: SELECT ip_address, array_to_json(array_agg(product_id)) as product_ids FROM impressions GROUP BY ip_address

 impressions_data = Impression.connection.execute('SELECT ip_address, array_to_json(array_agg(product_id)) as product_ids FROM impressions GROUP BY ip_address')
    impressions_data.each { |row| recommender.impressions.add_to_set(row['ip_address'], eval(row['product_ids'])) }

Can't migrate to heroku (Ruby on Rails tutorial [Michael Hartl] chaper 10)

I am working through chapter 10 of the Hartl book. In the conclusion of this chapter, we reset the heroku database and then migrate. However when I run:

heroku run rails db:migrate

I get an error:

rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::UndefinedColumn: ERROR:  column "password_digest_string" of relation "users" does not exist
: ALTER TABLE "users" DROP "password_digest_string"

Earlier in the tutorial, I removed a column called password_digest_string because it was named incorrectly and I didn't need it yet. It seems like rails is trying to delete the column again even though it isn't there anymore. I deleted the migration file that removed this column but it still is trying to drop it. What's also odd is that I've migrated the database several times since dropping that column and never had this issue until I reset it. Any suggestions?

Unable to get coffescript running, making a class into a link

So i am actually following a ruby on rail introductory video tutorial... This part of the course was about to teach me some coffeescript

So the plan is to make this grey container of the follow the same link as my "view answers"

the sample site

the code i am using is as below. i am also told that since i am using turbolinks i should include the "(document).on "page:load", ready" line

"home.coffee"

> ready = ->
> $(".media").on "click", -> 
>    (document).location = $(this).data("target")
>    return false

>$(document).ready(ready)
>$(document).on "page:load", ready

However, after testing it out. Clicking on the grey container, does nothing. Am i missing some sort of script for this to work? Earlier i tested out Console.log("TEST") on the coffee script , and it was able to print out on chrome's inspect .

Current layout of my pages

<!DOCTYPE html>
<html>
<head>
  <title>PROJECT HU</title>
<!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="http://ift.tt/2apRjw3" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>


  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <script src="http://ift.tt/2aHTozy" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  <script data-require="jquery@*" data-semver="2.1.3" src="http://ift.tt/13wBVXk"></script>

  <%= csrf_meta_tags %>
</head>

<body>
    <%= render 'home/navbar' %>

    <%= yield %> <!-- yield is content of the html-->
    <%= render 'home/new_question_form' %>

</body>

</html>

Index Page as below based on my tutorial, i had to add this data-target="<%= question_path(q) %>" into the media

<div class = "well">
    <h1>WELCOME LA</h1>
</div>
<div class='container'>
<!--#loop this html as much as number of question in the database-->
    <div class="boxes">
        <% @questions.each do |q|%> 
            <div class="media" data-target="<%= question_path(q) %>">
                    <div class="media-left">
                    <a href="#">
                        <img class="media-object" src="<%= q.gravatar%>" alt="sampleImg">

                    </a>
                    </div>
                    <div class="media-body">
                        <h4 class="media-heading"><%= q.email%> asked : </h4>
                        <div class="time"><%= time_ago_in_words q.created_at%></div>
                        <%= q.body %>
                    </div>

                    <div>
                        <a href= "<%= question_path(q)%>" class="btn btn-success btn-xs">View Answers</a>
                    </div>
            </div>
        <%end%>
    </div>
    <% if @questions.empty? %>
        <div class="alert alert-info">Ooops.... There's no questions here.</div>
    <% end %>
</div>

vendredi 20 janvier 2017

SimpleCov: load .resultset.json and output html

I would like to load a .resultset.json file and output the index.html that simplecov does when you run the test. I have not had success doing merging - it seems to only have the last result in the html coverage summary. I can create a resultset.json with multiple different keys and coverage under them, and I'd like to generate the html.

return data based on dates

I have controller that has

@account_info = @account_info.account_dates(params[:start_date], params[:end_date]) unless
params[:start_date].nil? || params[:end_date].nil?

Model has

self.table_name = 'UserAccounts'
scope :account_dates, -> (start_date, end_date) { where(account_date: start_date.to_date...(end_date.to_date + 1)) }

I have json created to display the data about account

accounts: [
{
name: "John"
account_date: "2016-12-27"
},
{
name: "Mike"
account_date: "2017-01-03"
},
{
name: "Jason"
account_date: "2014-01-01" 
}
]

start_date and end_date are optional parameters. right now if i dont pass them i get all the entries shown above which is one of the requirement. second requirement is if i just pass start_date e.g 2016-12-27 then i get the entries between start_date and todays date so i'll get 2016-12-27 and "2017-01-03" entries from json. I am new to rails. can someone help me how can i update my code for second requirement?

Thanks

Overwrite similar methods, shorter syntax

In a Ruby Class I overwrite 3 methods. As you can see in each method I basically do the same:

class ExampleClass

  def confirmation_required?
    is_allowed && super
  end

  def postpone_email_change?
    is_allowed && super
  end

  def reconfirmation_required?
    is_allowed && super
  end

end

Is there a more compact syntax? How can I shorten the code? Thanks

How to put Java Script variable in Erb method?

i have set onclick event on button through which i am calling a function otp(email.value) and passing input field email. On scripting side i want to put this email value in erb method.But i didnt found any method to do that.
please help me .

my code is
enter image description here

error in start a server in ruby on rails

when i want to start rails local server an error come :

DL is deprecated, please use Fiddle
Expected string default value for '--rc'; got false (boolean)
  create
  create  README.rdoc
  create  Rakefile
  create  config.ru
  create  .gitignore
  create  Gemfile
  create  app
  create  app/assets/javascripts/application.js
  create  app/assets/stylesheets/application.css
  create  app/controllers/application_controller.rb
  create  app/helpers/application_helper.rb
  create  app/views/layouts/application.html.erb
  create  app/assets/images/.keep
  create  app/mailers/.keep
  create  app/models/.keep
  create  app/controllers/concerns/.keep
  create  app/models/concerns/.keep
  create  bin
  create  bin/bundle
  create  bin/rails
  create  bin/rake
  create  config
  create  config/routes.rb
  create  config/application.rb
  create  config/environment.rb
  create  config/environments
  create  config/environments/development.rb
  create  config/environments/production.rb
  create  config/environments/test.rb
  create  config/initializers
  create  config/initializers/backtrace_silencers.rb
  create  config/initializers/filter_parameter_logging.rb
  create  config/initializers/inflections.rb
  create  config/initializers/mime_types.rb
  create  config/initializers/secret_token.rb
  create  config/initializers/session_store.rb
  create  config/initializers/wrap_parameters.rb
  create  config/locales
  create  config/locales/en.yml
  create  config/boot.rb
  create  config/database.yml
  create  db
  create  db/seeds.rb
  create  lib
  create  lib/tasks
  create  lib/tasks/.keep
  create  lib/assets
  create  lib/assets/.keep
  create  log
  create  log/.keep
  create  public
  create  public/404.html
  create  public/422.html
  create  public/500.html
  create  public/favicon.ico
  create  public/robots.txt
  create  test/fixtures
  create  test/fixtures/.keep
  create  test/controllers
  create  test/controllers/.keep
  create  test/mailers
  create  test/mailers/.keep
  create  test/models
  create  test/models/.keep
  create  test/helpers
  create  test/helpers/.keep
  create  test/integration
  create  test/integration/.keep
  create  test/test_helper.rb
  create  tmp/cache
  create  tmp/cache/assets
  create  vendor/assets/javascripts
  create  vendor/assets/javascripts/.keep
  create  vendor/assets/stylesheets
  create  vendor/assets/stylesheets/.keep
     run  bundle install
  DL is deprecated, please use Fiddle

after a few min an error come and say to install json gem and when i want install json gem an error come.what can i do to run server . ( my rails version :2.0.0 ruby version:2.0.0 )

jeudi 19 janvier 2017

Someone tried to hack a Rails website using invalid character in the url

Yesterday someone has tried hacking the website as there were around 200 requests which had byte sequence in it and were fired in less than 3 minutes from different urls of our own website.

We have one section of our website which is open to everyone without login and to proceed further one must login.

The error trace had this in most of the mails:

An ArgumentError occurred in #:

  invalid byte sequence in UTF-8
  vendor/bundle/ruby/2.1.0/gems/activesupport-3.2.14/lib/active_support/inflector/methods.rb:79:in `gsub!'


-------------------------------
Request:
-------------------------------

  * URL        : http://ift.tt/2jEZ59V
  * HTTP Method: GET
  * IP address : 182.19.8.82
  * Parameters : {"controller"=>"..\xC0\xAF..\xC0\xAF..\xC0\xAF..\xC0\xAF..\xC0\xAF..\xC0\xAF..\xC0\xAF..\xC0\xAFetc/passwd/io/vb", "action"=>"someurl_in_website"}
  * Timestamp  : 2017-01-19 17:30:47 +0000
  * Server : server
  * Rails root : /var/www/app
  * Process: 29648

-------------------------------
Session:
-------------------------------

  * session id: [FILTERED]
  * data: {"input_device_type"=>"MOUSE",
   "hover_supported"=>true,
   "incorrect_attempts"=>1,
   "locked"=>"false",
   "user"=>"qfswwjws",
   "flash_message"=>
    "Invalid User or Password !! Please note that your profile will be locked after 2 incorrect login attempts.",
   "session_id"=>"3774991d25843f57c90c2853712185a9"}

The data shown below is for sure sent by the user in the request as the URL which is being tried is not the login URL.

* data: {"input_device_type"=>"MOUSE",
   "hover_supported"=>true,
   "incorrect_attempts"=>1,
   "locked"=>"false",
   "user"=>"qfswwjws",
   "flash_message"=>
    "Invalid User or Password !! Please note that your profile will be locked after 2 incorrect login attempts.",
   "session_id"=>"3774991d25843f57c90c2853712185a9"}

Some other URL's from which the request came:

http://ift.tt/2iQ7p2h
http://ift.tt/2jEYd4W

The user was unable to hack into the website but how can we stop such attacks which can increase the server load for no reason?

How can we permanently block such users?

Rails Prawn UnrecognizedTableContent

after update Prawn 1.0.0.rc2 to 1.2.1

and install prawn-table

and start to

Prawn::Errors::UnrecognizedTableContent (Prawn::Errors::UnrecognizedTableContent):




table table_data do # , :cell_style => {:borders => [:bottom]}
  rows(0).style(size: 10, font_style: :bold, align: :center)
  rows(1).style(size: 10)
  self.column_widths = { 0 => 140, 1 => 100, 2 => 140, 3 => 70, 4 => 70 }
end

Rails query user first name on join model

this situation that find the user on a join model is seems tricky than usual

 class ConversationParticipant < ActiveRecord::Base
      belongs_to :user
      belongs_to :conversation
      attr_accessible :user_id
    end



   class User < ActiveRecord::Base
      has_many :conversation_participants

  end

I'm trying to find the conversation_participant with the fisrt_name with this query

 user = User.where('conversation_participant like ? or first_name like ?', query, query)

but the query did not return the user_participant and the user first_name either.

someone can spare a hint please!

Dynamic methods in ruby/rails

I'm developing a Rails application with ActiveRecord. Among other things, I have the following models:

class Report
  has_many :subscriptions
  has_many :custom_report_params
end

class CustomReportParam
  belongs_to :report
  # attributes are: :column_name, :variable_name, :description
end

class Subscription
  belongs_to :report
  # attributes (among others): :custom_text_field_1[,2,3], :custom_boolean_field_1[,2,3], :custom_date_field_1[,2,3]       
end

The tables are populated as below (for example):

reports
=======
id     name
 1     Test
 2     Test 2


custom_report_params
====================
id    report_id     column_name          variable_name     description     used
 1            1     custom_text_field1   test_param        Test Param         1

subscriptions
=============
id    report_id     custom_text_field_1
 1            1     test_param_value

Given this background, I want to create dynamic methods that will let me do the following:

r = Report.find(1)
s = r.subscriptions.first #=> returns the subscription object above

# this is the trouble part:
s.test_param #=> should return "test_param_value"

What I can already do, of course, is something like (over-simplified)

s.send(s.report.custom_report_params.used.first.column_name) #=> returns "test_param_value"

So.. in short, I want to define dynamic methods on an instance object using that objects associations to get the method names.

Will be happy to provide more clarification if needed.

I'm sort of familiar with dynamic methods. I already do something like:

["text", "boolean", "date"].each do |type|
  (1..3).each do |num|
    col_name = "custom_#{type}_field_#{num}"
    method_name = "#{col_name}_display
    send :define_method, method_name do
      case type
      when "text"
        self.send(col_name)
      when "date"
        self.send(col_name).try(:to_s, :date_format) || "XXX"
      when "boolean"
        self.send(col_name) ? "Yes" : "No"
      end
    end
  end
end

Any help would be appreciated.

Testing for nil value returned where query

I'm doing a query like this:

sla_field = CustomValue.where(:custom_field_id =>
  sla_field_id.id,:customized_id => params[:project_id])

And it's find when there are values, but if no value is present, where returns object that looks like this []

And if I try to test it like

sla_field.empty or sla_field.nil I get errors, how do I figure out did where query return something or not?

How would I write this SQL query in Rails 3.2 syntax?

I have the following code my Track.rb model. Is there any way to write this using more Rails syntax? Im using Rails 3.2

@track = Track.find(7)


Submission.joins("LEFT JOIN missions ON missions.id = submissions.mission_id")
          .joins("LEFT JOIN tracks ON tracks.id = missions.track_id")
          .where("missions.track_id = ?", track.id)

Models:

Track.rb
   has_many :missions

Mission.rb
   belongs_to :track
   has_many :submissions

Submission.rb
   belongs_to :mission

Rails 3.2 Asset Precompile is skipping files

Stack

  • Ruby 1.9.3
  • Rails 3.2.12

Issue

We have precompilation issues with our application.

We're trying to remove config.server_static_files = true and config.assets.compile = true from our production configs, but are constantly missing assets whenever we precompiled. Even though theses assets live in app/assets, while other files in the same directory are compiled fine.

Ex:

app/assets/stylesheets/application.css
app/assets/stylesheets/some_slider_lib.css
app/assets/stylesheets/bootstrap.min.css

After precompiling

public/assets/application-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.css
public/assets/some_slider_lib-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.css

And the manifest.yml is also missing the bootstrap file among other assets.

Same thing with our vendor folder.

Attempts

The following is the only way that I've managed to precompiles everything.

config.assets.precompile += ["*.css", "*.scss", "*.js", "*.coffee"]

However, this feels like overkill for something that, I think, should happen already.

If anyone could provide a little guidance, suggestions or more it would be deeply appreciated.

Thanks!

Rails render partial from sub-directory

I've just implemented the Devise Invitable gem in my rails app and now I'm having an issue getting my partials to render. I imagine it's because of absolute vs. relative paths.

I'm hesitant to change much in my application.rb since all of my other views rely on the partials that are being rendered. So, is there another way to make this all work?

Here is the directory tree:

app/
 -controllers/
 ---application_controller.rb
 ---users/
 -----invitations_controller.rb
 -views/
 ---layouts/
 -----application.html.erb
 -----_back_buttons.html.erb
 -----_footer.html.erb
 -----_navigation.html.erb
 ---users/
 -----invitations/
 -------new.html.erb
 -------edit.html.erb

In my application.rb file, I'm currently rendering views & partials with:

<%= render partial: 'layouts/navigation' %>
<%= render partial: 'layouts/topnav' %>
<%= render partial: 'layouts/tour' %>

<%= yield %>

<%= render partial: 'layouts/footer' %>
<%= javascript_include_tag 'footermanifest' %>

And in my new view views/users/invitations/new.html.erb:

<%= render partial: "/layouts/back_button" %>
... the form

Notice the absolute reference to the partial here (/)

This loads the layouts/_back_button.html.erb fine, but none of the other partials in application.html.erb load. Basically, I have a pretty empty page with a form (courtesy of application.html.erb).

Am I doing something wrong in how I've nested the views/users/invitations/new.html.erb or something else?

rails select helper without square brackets

If I create select tag like this select(:project_id, nil, in a Rails view file,

in my generated html I get name of select field like project_id[] but I want just project_id,

how do I do that?

Gem Chewy update_index observer not working in rails app

I am using Elasticsearch 5.1 and gem Chewy, Import works perfectly while delete -> create -> import records. But while I try to add the observer in my model it's not updating the index. Did not found any clue how can I fix this or trace my problem.

I tried the following code snippet for the observer

class Product < ActiveRecord::Base
   update_index(ProductsIndex::Product) { self }
end

OR

class Product < ActiveRecord::Base
   update_index('products#product') { self }
end

I am using strategy as :urgent and the following mappings

class ProductsIndex < Chewy::Index

   settings analysis: {
         analyzer: {
           case_insensitive: {
             tokenizer: "keyword",
             filter: ["lowercase"]
           },

           lowercase_space_analyzer: {
             type: "custom",
             tokenizer: "whitespace",
             filter: ["synonym", "lowercase"]
           }
         }
       }

  define_type Product.includes(:job) do
     default_import_options batch_size: 100, bulk_size: 10.megabytes, refresh: true
     field :title, :heading, :ingress, :description, :job_language
     field :location, value: ->(product) { (product.location||"") }
     field :company_name, value: ->(product) { product.job.company.name }
     ........    
  end

end

Product class using single table inheritance and has some child class as following

class Product::Norway < Product
   ......
end

When I create/update Product nothing happen, how can I get ride of this?

mercredi 18 janvier 2017

Unpermitted parameters from nested attributes

I've looked through every post I can imagine regarding this, but can't come across a solution. I have a Task with a nested resource of Task Products which grabs its ID's from another database. There can be multiple Task Products nested in a Task, and each one is dynamically created with some Javascript and an Application Helper (both of which are purely a copy/paste on my part).

I built up the code for these nested parameters with the help of Railscast 196/197 and this post. All the relevant code is below, and then onto the problem:

task.rb:

class Task < ApplicationRecord
  has_many :task_products, :dependent => :destroy
  accepts_nested_attributes_for :task_products, :reject_if => lambda { |p| p.values.all?(&:blank?) }, :allow_destroy => true
end

task_controller.rb:

class TasksController < ApplicationController

  def new
    @task = Task.new
    @task.task_products.build
  end

    def task_params
  params.require(:task).permit(:id, :task_name, . . ., :created_at, :updated_at, 
                               :task_products_attributes => [:task_id, :product_id, :created_at, :updated_at])
end

application_helper.rb:

module ApplicationHelper

  def new_child_fields_template(form_builder, association, options = {})
    options[:object] ||= form_builder.object.class.reflect_on_association(association).klass.new
    options[:partial] ||= association.to_s.singularize
    options[:form_builder_local] ||= :f

    content_tag(:div, :id => "#{association}_fields_template", :style => "display: none") do
      form_builder.fields_for(association, options[:object], :child_index => "new_#{association}") do |f|
        render(:partial => options[:partial], :locals => { options[:form_builder_local] => f })
      end
    end
  end

application.js:

$(function() {
  $('form a.add_child').click(function() {
    var association = $(this).attr('data-association');
    var template = $('#' + association + '_fields_template').html();
    var regexp = new RegExp('new_' + association, 'g');
    var new_id = new Date().getTime();
    $(this).parent().before(template.replace(regexp, new_id));
    return false;
  });
});

_form.html.erb:

<%= form_for @task, url: tasks_path, method: :post, :html => {:multipart => true } do |f| %>
    <%= f.fields_for :task_products, TaskProduct.new do |builder| %>
      <%= render "task_product", :f => builder %>
    <% end %>
    <p><%= add_child_link "Add Product", :task_products %></p>
    <%= new_child_fields_template f, :task_products %>

_task_product.html.erb:

<div class="fields">
  <div class="form-group">
    <%= f.label :product_id, "Product:", class: 'col-sm-3 control-label' %>
      <%= f.collection_select(:product_id, @items, :id, :item_select, {:include_blank => 'Select Item...'}, {:class => 'form-control'}) %>
      <%= remove_child_link "Remove Product", f %>
  </div>
</div>

Code in console after submit along with the error it produced:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"KDQ...8bxur2A==", 
"task"=>{"task_type"=>"Store Order", 
    "task_products_attributes"=>{
    "0"=>{"product_id"=>"1", "_destroy"=>"false"}, 
    "1484792726712"=>{"product_id"=>"2", "_destroy"=>"false"}, 
    "new_task_products"=>{"product_id"=>"", "_destroy"=>"false"}}, 
    "initiated_by"=>"1", "initiated_for"=>"5", "active"=>"true", "status"=>"Pending Acceptance"}, 
"commit"=>"Create Task"}

Unpermitted parameters: 0, 1484792726712, new_task_products

Generated HTML examples of error producing code of multiple generated selects:

<select class="form-control" name="task[task_products_attributes][0][product_id]" id="task_task_products_attributes_0_product_id">
<select class="form-control" name="task[task_products_attributes][1484794199756][product_id]" id="task_task_products_attributes_1484794199756_product_id">

and its template, which I thought should be throwing back ' "_destroy"=>true' in the console?:

<select class="form-control" name="task[task_products_attributes][new_task_products][product_id]" id="task_task_products_attributes_new_task_products_product_id">

The problem, as seen above, is that my generated Task Product form is adding an additional bracketed identifier(child index?) into my select box for each item, and I don't know how to dive into the Application Helper to remove it, or move it where it belongs. Or does it actually belong there and I'm doing something else wrong? I get the feeling that each individual Task Product should have it's own unique identifier, but Rails isn't having any of that and says its unpermitted.

The 'new_child_fields_template' in the Application Helper is a bit over my head, and while I understand how it's getting the unique identifier to inject into my Task Product form, I don't know how it's throwing it into the "name=" field of my select that is apparently screwing everything up. Anybody have some guidance on how I can overcome this problem? Thanks!

Render HTML executing the HTML of the page

My page has javascript embedded and I need to render js along with the html page.

Follow the code that I am using to render my page:

render :update do |page|
  get_custom_categories
  element = params[:modal].present? ? ".modal-body .object-show" : ".object-show"
  page[element].js(render partial: 'details_edit')
 end

HTML execute Ruby Script

I have a basic rails website, generated using rails new app_name. I want to execute a ruby scraper script that returns a list of my github repos from a client side action. Such as a hover or a click on an element. How do I go about doing this?

I've read about rails rake tasks and have the scraper script and webpage up and functioning. However as far as putting it all together goes i'm lost, and at most unsure if what i'm doing is the correct way to be going about things.

Would someone be able to help me understand how to execute a ruby script that 'puts "Hello World!"' on click on the server side which is then displayed on the client side? Any help is appreciated, thank you!

config.expire_auth_token_on_timeout not working in devise 3.2.4 with rails 3.2.13

Using devise 3.2.4 with rails 3.2.13.

I am trying to expire auth token on session timeout therefore in my devise.rb file , I have made following changes :-

config.timeout_in = 1.minutes config.expire_auth_token_on_timeout = true

The timeout works perfectly, user is logged out after 1 minute of inactivity period but the auth token is not expiring on timeout.

Here is the user model:-

  devise :database_authenticatable, :async , :registerable, :confirmable,
     :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :timeoutable  

Any idea what I am missing ?

RSpec Stack level too deep (SystemStackError)

I have three models offer_ticket, event and offer and have three their respective factories below are the models and factories are given i got error stack level too deep suggest me a solution how to remove this error

offer_ticket.rb

class OfferTicket < ActiveRecord::Base
    belongs_to :event
end

event.rb

class Event < ActiveRecord::Base
   has_many :offer_tickets , dependent: :restrict_with_error
end

offer.rb

class Offer < ActiveRecord::Base
   has_many :offer_tickets , dependent: :restrict_with_error
end

Their respective factories as given below

offer_tickets.rb

FactoryGirl.define do
   factory :offer_ticket do
      venue_row_id        1
      sale_id             1
      status              "available"
      seat_number         1
      association(:event)
   end
end

events.rb

FactoryGirl.define do
   factory :event do |f|

      f.name { Faker::Name.name  }
      f.starts_at { Faker::Date.backward(Random.rand(20)).to_date }
      f.description { Faker::Lorem.paragraph }
      after(:build) do |event|
         create(:offer, event: event)
      end
   end
 end

offers.rb

FactoryGirl.define do
  factory :offer do
    price                   1
    proxy                   1
    multiple                1
    cancelothers            1
    after(:build) do |offer|
       create(:offer_ticket, offer: offer)
    end
  end

end

When run below command in terminal got an error stack toop deep level

rspec spec/models/offer_ticket_spec.rb
/home/aqib/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/activerecord-4.1.1/lib/active_record/connection_adapters/abstract/database_statements.rb:222: stack level too deep (SystemStackError)

disable rubocop error 'Use find_by instead of where.first' for rails 3.2 project

I am using rubocop that shows error Use find_by instead of where.first. My rails version is 3.2 that does not support find_by method that's why I am trying to disable this. I have tried using following configuration with in my .rubocop.yml file but did not work

Rails: Enabled: false

Does anyone has any idea how can I disable above error for rubocop? Any kind of help is appreciated. Thanks.

mardi 17 janvier 2017

Rail Active admin and BCrypt Gem, how to decrypt a password?

I am using rails active admin gem and BCrypt Gem. Now I want to decrypt all users password.How can I do this?

Thanks your support!!

how to get god status in rails

I have setup god and provided script file to load and it working as expected. i wanted to take status of that god process from my rails application.

I am not able to take god status from my rails controller.

my code

require 'god'
class HomesController < ApplicationController
  def status_check
    God::status
  end
end

but this gives me error uninitialized constant HomesController::God

Please help me to call god status from my web application.

NameError in CoursesController#index

I was taking the course on ruby on rails from courser and i encountered this error which was not even mentioned on FAQs page. I am posting model files, view files and controller files. Please provide me a solution to it.The error i got when i typed www.localhost:3000/courses/index is given in this screenshot. Click here

            courses_controller.rb
class CoursesController < ApplicationController
   def index
        @search_term = params[:looking_for] || 'jhu'
        @courses = Coursera.for(@search_term)
   end
end


                 coursera.rb

class Coursera
   include HTTParty
   default_options.update(verify: false) # Turn off SSL verification
   base_uri 'http://ift.tt/1OxnZ5U'
   default_params fields: "smallIcon,shortDescription", q: "search"
   format :json

   def self.for term
      get("", query: { query: term})["elements"]
   end
end

              index.html.erb
<h1>Searching for - <%= @search_term %></h1>
<table border="1">
   <tr>
       <th>Image</th>
       <th>Name</th>
       <th>Description</th>
   </tr>
   <% @courses.each do |course| %>
      <tr class=<%= cycle('even', 'odd') %>>
          <td><%= image_tag(course["smallIcon"])%></td>
          <td><%= course["name"] %></td>
          <td><%= course["shortDescription"] %></td>
      </tr>
   <% end %>
</table>

lundi 16 janvier 2017

paypal adaptive Authentication+failed.+API+credentials+are+incorrect

i'm testing the adaptive payment on sandbox mode. but i'm getting error=Authentication+failed.+API+credentials+are+incorrect

so, i would like to know where i get the password and signature for the sanbox? because on paypal developer website did not show.

my configuration is:

mode: sandbox

# Credentials for Classic APIs
app_id: APP-MY SANBOXAPP
username: [github]
password: WX4WTU3S8MY44S7F = DEFAULT FROM [github]
signature: AFcWxV21C7fd0v3bYYYRCpSSRl31A7yDhhsPUU2XhtMoZXsWHFxu-RWy = DEFAULT FROM [github]

sandbox_email_address: [github]

Error installing rmagick 2.13.x - Rails

I'm trying to install rmagick 2.13.x and I'm having a few problems. I've installed imagemagick and libmagickwand-dev.

I have two folders with imagemagick (I don't know why, I've installed it with make, make install)

/usr/include/ImageMagick-6 /usr/local/include/ImageMagick-7

I'm using ruby 2.2.3 and when I run gem install rmagick 2.13.4 (also, I've tried with 2.13.2, 2.13.3), these errors appear at the end

====================================================================== Mon 16Jan17 21:41:54 This installation of RMagick 2.13.4 is configured

for Ruby 2.2.3 (x86_64-linux) and ImageMagick

make "DESTDIR=" clean

make "DESTDIR=" compiling rmagick.c In file included from rmagick.c:13:0: rmagick.h:1206:51: error: unknown type name ‘MagickPixelPacket’ extern void Color_to_MagickPixelPacket(Image *, MagickPixelPacket *, VALUE); ^ rmagick.h:1215:1: warning: parameter names (without types) in function declaration extern VALUE FilterTypes_new(FilterTypes); ^ rmagick.h:1220:50: error: unknown type name ‘MagickPixelPacket’ extern VALUE Pixel_from_MagickPixelPacket(const MagickPixelPacket *); ^ rmagick.h:1236:1: warning: parameter names (without types) in function declaration extern VALUE InterpolatePixelMethod_new(InterpolatePixelMethod); ^ rmagick.h:1249:1: warning: parameter names (without types) in function declaration extern VALUE LAYERMETHODTYPE_NEW(LAYERMETHODTYPE); ^ rmagick.h:1285:51: error: unknown type name ‘MagickPixelPacket’ void rm_set_magick_pixel_packet(Pixel *, MagickPixelPacket ); ^ rmagick.c: In function ‘MagickInfo_to_format’: rmagick.c:136:26: error: ‘MagickInfo {aka const struct _MagickInfo}’ has no member named ‘blob_support’ mode[0] = magick_info->blob_support ? '': ' '; ^ rmagick.c:139:50: error: ‘MagickInfo {aka const struct _MagickInfo}’ has no member named ‘adjoin’ mode[3] = magick_info->encoder && magick_info->adjoin ? '+' : '-'; ^ Makefile:237: recipe for target 'rmagick.o' failed make: *** [rmagick.o] Error 1

make failed, exit code 2

Gem files will remain installed in /home/lucas/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rmagick-2.13.4 for inspection. Results logged to /home/lucas/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/extensions/x86_64-linux/2.2.0-static/rmagick-2.13.4/gem_make.out

adaptivepayments-sdk-ruby undefined method `[]' for false:FalseClass

.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/paypal-sdk-core-0.3.4/lib/paypal-sdk/core/config.rb:209:indefault_config': undefined method []' for false:FalseClass (NoMethodError)

after installing it and place the rails g paypal:sdk:install command show this error.

someone with the same issue?

dimanche 15 janvier 2017

Error Transaction.new into Rails app trying to import CSV data

I try to import a CSV file into my database in a Rails app. I follow this gist.

Here is my code:

# db/seeds.rb
require 'csv'

csv_text = File.read(Rails.root.join('lib', 'seeds', 'siren_db.csv'))
csv = CSV.parse(csv_text, :headers => true, :encoding => 'ISO-8859-1')
csv.each do |row|
  t = Transaction.new
  t.siren = row['siren']
  t.nom = row['nom']
  t.adresse = row['adresse']
  t.complement_adresse = row['complement_adresse']
  t.pays = row['pays']
  t.region = row['region']
  t.departement = row['departement']
  t.activite = row['activite']
  t.date = row['date']
  t.nb_salaries = row['nb_salaries']
  t.nom = row['nom']
  t.prenom = row['prenom']
  t.civilite = row['civilite']
  t.adr_mail = row['adr_mail']
  t.libele_acti = row['libele_acti']
  t.categorie = row['categorie']
  t.tel= row['tel']
  t.save
  puts "#{t.siren}, #{t.nom} saved"
end

puts "There are now #{Transaction.count} rows in the transactions table"

Unfortunately, I have an error but don't know why? (I have the exact same code as the gist) :

rake aborted! NameError: uninitialized constant Transaction /Users/nicolasleroux/Public/sites/sirenforest/db/seeds.rb:6:in block in ' /Users/nicolasleroux/Public/sites/sirenforest/db/seeds.rb:5:in' Tasks: TOP => db:seed (See full trace by running task with --trace)