mardi 28 février 2017

nested routes is working different in rails 3.2 and rail 4

I am using rails 3.2 and having the following routes

resources :projects do  
  resources :assessments  
end 

Now when I am using project_assessment_path(@assessment) in the view, it's assigning some ID as project_id(sample generated path projects/1/assessments/2)

I can't figure out how it's getting the project_id, but when I move to Rails 4 it's giving me the error ActionController::UrlGenerationError - No route matches which is quite expected. But I am wondering how it's working in rails 3.2

How to send mail in Rails use Gmail and Proxy

I want to send mail via Gmail with proxy. Someone give a keyword or docs to resolve this solution.

Remove users from database (Ruby on Rails, Devise)

I'm trying to create a button to remove users from the database.

In the routes I have:

  devise_for :users, :controllers => { registrations: 'registrations' }
  match 'users/:id' => 'registrations#destroy', :via => :delete, :as => :admin_destroy_user

registration_controller:

def destroy
    @user = User.find(params[:id])
    if @user.destroy
      redirect_to root_path
    end
end

_backoffice.html.erb file:

<%= button_to 'Delete', admin_destroy_user_path(user.id), :class => 'btn btn-danger btn-sm', :method => :delete, data: {:confirm => 'Tem a certeza que quer apagar este utilizador?'} %>

And this is the error I'm getting:

NoMethodError in RegistrationsController#destroy

undefined method `name' for nil:NilClass

  def resource_name
    devise_mapping.name
  end
  alias :scope_name :resource_name

Thanks for any help.

Different ways of rendering collection of records rails

I'm trying to render a collection of elements using partials in rails. I found 3 approaches that work, but not all for the same html document. These are the approaches that I found working, but I don t understand why some work in some files and some dont.

<%= j render @event_messages %>

<%= render @event_messages%>

<%= render partial: 'event_message', collection: @event_messages%>

Let's say I have the html file index.html.erb and the partial _event_message.html.erb. Now I'll go over the 3 approaches:

<%= render partial: 'event_message', collection: @event_messages%> this line works perfectly in this case and the partial gets rendered as many times as required.

<%= render @event_messages%> throws the missing template error, but in other .html.erb files I can use it to render partials with no problems.

<%= j render @event_messages %> works in a .js.erb file, but what does the 'j' stand for? I'm using this approach with an ajax callback and for some cases it works, but for others I get the missing template error.

Missing partial event_messages/_event_message with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in:

I tried my best to describe the issue. If you need more information, just let me know.

rvm list known differs between develop and production

I was planing to upgrade my ruby version for a project. On 1.9.3 so was thinking it was good idea to do in steps. First step would be 2.0.0, I run rvm list known and get this

...
[ruby-]1.9.3[-p551]
[ruby-]2.0.0[-p648]
[ruby-]2.1[.1 
...

But when I run the same command on my production server I get

[ruby-]1.9.2[-p330]
[ruby-]1.9.3[-p547]
[ruby-]2.0.0-p481
[ruby-]2.0.0[-p576]
[ruby-]2.1.2

Why do these list differs ? Seems like it would be a good idea to use the same version on both dev and prod

i want to start development in ruby on rails but not sure how to setup my dev environment

I want to start development in ruby on rails and I need to setup my development environment but I am confuse because I can't decide to use online ide or setup it locally.

I am using windows 10 .

Rails - run method only after a specific attribute's JSON field is updated

I'm trying to run a method in Rails only after the JSON field search_terms of the settings attribute is updated.

The model's name is Campaign and this is an example of an instance's attributes:

Campaign.first.attributes

=> {
               "id" => 1,
             "name" => "example.com",
           "status" => "on",
        "languages" => [],
          "country" => nil,
         "settings" => {
                   "search_terms" => {
            "happy" => true,
            "sad" => true,
              "excited" => true
        },
        "keyword_refresh_intervals" => {
            "en-us" => 60,
            "ru-ru" => "0",
            "en-gb" => "0"
        }
    },
    "advertiser_id" => 1,
       "created_at" => Sun, 25 Dec 2016 10:55:47 UTC +00:00,
       "updated_at" => Tue, 28 Feb 2017 08:07:05 UTC +00:00
}

In the Campaign model itself I'm executing the required Job after a commit is made:

class Campaign < ApplicationRecord
  after_commit -> { PlacementsGeneratorJob.perform_later }

But I want it to be executed only after the search_terms value is changed in the settings attribute and not when the whole settings attribute is changed.

Is that even possible?

Using Partial View's Controller Instead

I'm trying to use partial view's controller instead of the view where I render it. My scenario is as following;

I have users and users can post something. Thats why I've two controller and models (users and post).

In the user's page, there is a textarea to get input of content and button to post . I've written this view .../views/posts/_new.html.erb as partial view and I render this partial in the .../views/users/index.html.erb and to use partial view I've used this piece of code.

<%= render 'posts/new' %>

In order to create post, I've written this method;

posts_controller.rb

  def new
    @post = Post.new
  end

  def edit
    @post = Post.find(params[:id])
  end

  def create
    @user = User.find(params[:user_id])
    @post = @user.posts.create(post_params)

    if @post.save
      redirect_to root_path
    else
      render 'new'
    end
  end

.../views/posts/_new.html.erb

<%= form_for :post do |f| %>
          <%= f.text_area :content, :class => "form-control", "rows" => "5", "id" => "comment", "placeholder" => "Write something to share with your mates ..." %><br/>
          <%= button_tag  "Share", :class => "btn btn-primary pull-right" do %>
            <span class="glyphicon glyphicon-share-alt"></span>
          <% end %>
        <% end %>

The problem here is, when I click the button in partial view, it goes to Users#RegistrationController of devise controller. Why ?

Here, guide tells that if there is a relationship between partials and the view that renders it, rails understands what we want to do and and use partial view's controller instead. Am I missing something here ?

lundi 27 février 2017

How to deploy rails application running locally(on my laptop) to live server (of my university) for local access

I am building an application for the students of my university. I am using ruby on rails for this and that application is running on my laptop at http://localhost:3000/ Now we have servers running in our university and I want to deploy my rails application on those servers so that students can access the application locally in the university. I am new to rails so please help me in doing this.

Thanks in advance

Problems with Stripe Gem

I'm getting this error message whenever I tried to start Rails server after installing Stripe gem.

rails s /home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe.rb:23:in `require': /home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:20: syntax error, unexpected tLABEL (SyntaxError) ...alize(message=nil, http_status: nil, http_body: nil, json_bo... ... ^ /home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:20: Can't assign to nil ...(message=nil, http_status: nil, http_body: nil, json_body: n... ... ^ /home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:20: Can't assign to nil ...tp_status: nil, http_body: nil, json_body: nil, ... ^ /home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:20: Can't assign to nil /home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:39: class definition in method body /home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:45: class definition in method body /home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:52: class definition in method body /home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:57: class definition in method body /home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:60: syntax error, unexpected tLABEL ...sage, param, code, http_status: nil, http_body: nil, json_bo...

I think that is a problem with my ruby version which is 1.9.3, as far as I know Stripe doesn't support ruby version 1.9, but I haven't find anything concrete about this. Do you guys know if is possible to have Stripe working with ruby 1.9?

Thank you!

Rails Localhost not working

So when I run "rails server" and try to open any project, i get this error when trying to open localhost:3000 : Error

But this is what my terminal says:

The thing is I thought it was because me pushing to git heroku was causing it to fail so another form said to uninstall heroku, however that didn't work and i still get this error.

$ rails s

=> Booting Puma
=> Rails 5.0.1 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
/Users/User/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activesupport-5.0.1/lib/active_support/core_ext/numeric/conversions.rb:138: warning: constant    ::Fixnum is deprecated
[27508] Puma starting in cluster mode...
[27508] * Version 3.7.0 (ruby 2.4.0-p0), codename: Snowy Sagebrush
[27508] * Min threads: 5, max threads: 5
[27508] * Environment: development
[27508] * Process workers: 2
[27508] * Preloading application
[27508] * Listening on tcp://0.0.0.0:3000
[27508] Use Ctrl-C to stop
[27508] - Worker 1 (pid: 27544) booted, phase: 0
[27508] - Worker 0 (pid: 27543) booted, phase: 0

Before, rails server would just stop at "Use Ctrl-C to stop" but it now has these worker id's and stuff. They probably happened when I installed heroku and tried to push my project with git heroku. What do those workers mean for future reference and how can I connect to localhost again?

What I've tried so far based on other stackexchange suggestions:

  1. Uninstalling heroku
  2. Deleting the heroku apps (these fail since they say there are no apps found even with the entire name used)
  3. Commenting out the line "config.force_ssl = true" inside app/config/environments/production.rb
  4. Deleting Procfile

Note: I've been following Michael Hartl's tutorial, specifically Chapter 7 http://ift.tt/1muevdZ And tried to do the SSL section and this is when I encountered errors.

OpenSSL Error - read finished A decryption failed or bad record mac

I am using RestClient to access an external API using a certificate available. I have useed it like this,


require 'rest-client'

p12 = OpenSSL::PKCS12.new(File.read('/root/cert.p12'), 'password')

RestClient::Request.execute(method: :post, url: "https:myurl.com", ssl_client_cert: p12.certificate, ssl_cert_key: p12.key, payload: { data: "" }, verify_ssl: OpenSSL::SSL::VERIFY_NONE)

On doing the above steps, I get :


OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read finished A: decryption failed or bad record mac

Can someone help me out in this?

Job failed with status 1 (command: app_dir/script/runner -e production namespace.task_name

Job failed with status 1 (command: app_dir/script/runner -e production namespace.task_name

The above error I am getting in my syslog, my cronjob this task is getting failed.

Please can anyone suggest where I am doing wrong.

The production mode ruby app doesn't run, unicorn and nginx

I'm going to deploy my ruby on rails app on my own server. So i decided to follow this tutorial that is from degital ocean:

http://ift.tt/1bxHj0A

I configured my database.yml which i add host:localhost and configured rben-var in my app directory and Migrate the production database very well. I couldn't start the rails with this command RAILS_ENV=production rails server And i thought maybe it is because of my last time that I set the unicorn as default for my another app(you know i have two other app which i deploy them on the server well but i removed their path from the nginx) then I create config/unicorn.rb finally when I started sudo vi /etc/init.d/unicorn_drug it gives me this error:

master failed to start, check stderr log for details

When i see the log which Is in /shared/log/unicorn.stderr.log i see following error lines. You know i spend two days on this case but I really can't understand what is the error is:

  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:752:in `call'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:752:in `build_app!'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:129:in `start'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/bin/unicorn:126:in `<top (required)>'
  /root/.rbenv/versions/2.2.3/bin/unicorn:23:in `load'
  /root/.rbenv/versions/2.2.3/bin/unicorn:23:in `<top (required)>'
I, [2017-02-27T13:38:21.860366 #1848]  INFO -- : Refreshing Gem list
NameError: uninitialized constant RegistrationController
  /root/drug_api/app/controllers/RegistrationController/confirmations_controller.rb:1:in `<top (required)>'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-5.0.1/lib/active_support/dependencies/interlock.rb:12:in `block in loading'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-5.0.1/lib/active_support/concurrency/share_lock.rb:150:in `exclusive'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-5.0.1/lib/active_support/dependencies/interlock.rb:11:in `loading'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/engine.rb:476:in `block (2 levels) in eager_load!'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/engine.rb:475:in `each'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/engine.rb:475:in `block in eager_load!'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/engine.rb:473:in `each'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/engine.rb:473:in `eager_load!'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/engine.rb:354:in `eager_load!'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/application/finisher.rb:59:in `each'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/application/finisher.rb:59:in `block in <module:Finisher>'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/initializable.rb:30:in `instance_exec'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/initializable.rb:30:in `run'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/initializable.rb:55:in `block in run_initializers'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:226:in `block in tsort_each'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:348:in `block (2 levels) in each_strongly_connected_component'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:429:in `each_strongly_connected_component_from'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:347:in `block in each_strongly_connected_component'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:345:in `each'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:345:in `call'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:345:in `each_strongly_connected_component'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:224:in `tsort_each'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:203:in `tsort_each'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/initializable.rb:54:in `run_initializers'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/application.rb:352:in `initialize!'
  /root/drug_api/config/environment.rb:5:in `<top (required)>'
  config.ru:4:in `require_relative'
  config.ru:4:in `block in <main>'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rack-2.0.1/lib/rack/builder.rb:55:in `instance_eval'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rack-2.0.1/lib/rack/builder.rb:55:in `initialize'
  config.ru:1:in `new'
  config.ru:1:in `<main>'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn.rb:56:in `eval'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn.rb:56:in `block in builder'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:752:in `call'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:752:in `build_app!'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:129:in `start'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/bin/unicorn:126:in `<top (required)>'
  /root/.rbenv/versions/2.2.3/bin/unicorn:23:in `load'
  /root/.rbenv/versions/2.2.3/bin/unicorn:23:in `<top (required)>'

dimanche 26 février 2017

Ruby On Rails - how to compromise the modularity of the code?

I was in an interview for an internship last week and I was given a part of ruby on rails code of a controller. Then the interviewer asked me to "compromise modularity of the code". I was stuck on this question so that I am looking for the answer of this question now. Can someone please explain what is "compromise modularity of the code"?

Creating form that changes multiple models

So I have an assignment where I have to build an app with Ruby on Rials and i'm having some trouble with using forms.. The app basically is a video site that lets users upload a video URL and comment on these videos.

This is the database:

ActiveRecord::Schema.define(version: 20170226161051) do

  create_table "comments", force: true do |t|
    t.text     "body"
    t.integer  "video_id"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "comments", ["user_id"], name: "index_comments_on_user_id"
  add_index "comments", ["video_id"], name: "index_comments_on_video_id"

  create_table "users", force: true do |t|
    t.string   "name"
    t.string   "mailaddress"
    t.string   "birthday"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "videos", force: true do |t|
    t.string   "title"
    t.string   "url"
    t.text     "description"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

Here are the models:

class Comment < ActiveRecord::Base
  belongs_to :video
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :comments
end

class Video < ActiveRecord::Base
  has_many :comments
end

The user controller:

class UsersController < ApplicationController
  def new
    @user = User.new
  end
end

The video controller:

class VideosController < ApplicationController

  def new
    @video = Video.new
  end

  def create
    @video = Video.new(video_params)

    if @video.save
      redirect_to @video
    else
      render 'new'
    end
  end

  def show
    @video = Video.find(params[:id])
  end

  def index
    @video = Video.all
  end

  def edit
    @video = Video.find(params[:id])
  end

  def update
    @video = Video.find(params[:id])
    if @video.update(params[:video].permit(:title, :url, :description))
      redirect_to @video
    end
  end

  def destroy
    @video = Video.find(params[:id])
    @video.destroy

    redirect_to videos_path
  end

  private
    def video_params
      params.require(:video).permit(:title, :url, :description)
    end 

end

And the comment controller:

class CommentsController < ApplicationController
  def create
    @video = Video.find(params[:video_id])
    @comment = @video.comments.create(params[:comment].permit(:body))
    redirect_to video_path(@video)
  end
end

Now I'm trying to make a form where a user can give a username (without any form of authentication) and a comment. I've managed to make a form that lets the user upload comments, without any username, but I've been having a lot of trouble with adding a username. This is what I have in my view so far:

<h1>
  <strong>Title:</strong>
  <%= @video.title %>
</h1>

<p>
    <%= video_tag @video.url, controls: true, autobuffer: true %>
</p>

<p>
  <strong>Description</strong>
  <%= @video.description%>
</p>

<h2>Comments</h2>
<% @video.comments.each do |comment|%>
    <p>
        <%= comment.body %>
    </p>
<%end%>

<h2> Add a comment</h2>
<%= form_for([@video, @video.comments.build]) do |f|%>

    <p>
        <%= f.label :body %><br />
        <%= f.text_area :body %>
    </p>

    <p>
        <%= f.submit %>
    </p>
<% end %>

<%= link_to 'Back to list of videos', videos_path %>

I've googled this problem and some people have had the same problem, but I can't seem to find a solution that works for me.

samedi 25 février 2017

How can i pass array to function in ruby and why is the output not as expected for my code

This is my code and why is it giving something extra with required output

How to add a single custom route in rails?

I have transaction model, controller with view, which I created with rails generate. Now I need to add a single custom route of /transactions/history to my application to be handled by a controller def history:... end and render history.html.erb

So added this line in my routes.rb:

get '/transactions/history', to: 'transactions#history', as: 'transactions_history'

And this in my transactions_controller.rb:

def history
    @transactions = Transaction.all
end

and created a history.htmk.erb in transactions->views

I also see this line when calling rake routes:

transactions_history GET    /transactions/history(.:format)                 transactions#history

But when I request localhost:3000/transactions/history in my browser, it gives me the following error:

Couldn't find Transaction with 'id'=history

and I also see this line in logs:

Request info

Request parameters  
{"controller"=>"transactions", "action"=>"show", "id"=>"history"}

Why it is calling the 'show' action in my transaction controller?

How to assign role to user in Registration Controller and its view with Rolify and Devise

I want to have radiobuttongroup to choose role in my view but im not sure how to handle it. I've already setup the gems rolify and devise but Im not sure how to assign roles in view and controller. I've already created roles in console. I want to make sure that there isn't any exploits when choosing role. For example, if the person tries to change role name from browser and assign that to himself(e.g. admin), that would be a big problem.

registrations_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: [:create]

  def create
    super
  end

  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:firstname, :lastname, :email, :terms_of_service])
  end

user.rb

class User < ApplicationRecord
  rolify

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable, :lockable, :timeoutable
  validates :terms_of_service, :allow_nil => false, :acceptance => true

end

part of view for registration

<%= form_for(resource, as: resource_name, :role => "form", url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>
  <div class="form-group">
    <%= f.label t('label.user.form_content.firstname') %><br/>
    <%= f.text_field :firstname, autofocus: true, :class => "form-control text-center" %>
  </div>
  <div class="form-group">
    <%= f.label t('label.user.form_content.lastname') %><br/>
    <%= f.text_field :lastname, :class => "form-control text-center" %>
  </div>
  <div class="form-group">
    <%= f.label t('label.user.form_content.email') %><br/>
    <%= f.email_field :email, :class => "form-control text-center" %>
  </div>
  <div class="row">
    <div class="col-md-6">
      <div class="form-group">
        <%= f.label t('label.user.form_content.password') %>
        <% if @minimum_password_length %>
            <em>(<%= @minimum_password_length %> characters minimum)</em>
        <% end %><br/>
        <%= f.password_field :password, autocomplete: "off", :class => "form-control text-center" %>
      </div>
    </div>
    <div class="col-md-6">
      <div class="form-group">
        <%= f.label t('label.user.form_content.password_confirmation') %>
        <% if @minimum_password_length %>
            <em>(Must be same with password)</em><br/>
        <% end %><br/>
        <%= f.password_field :password_confirmation, autocomplete: "off", :class => "form-control text-center" %>
      </div>
    </div>
  </div>
<% end %>

vendredi 24 février 2017

(Errno::EACCES) Permission denied with pygments.rb

I have been really struggling with installing pygments.rb and did not find solution whatsoever. I'm a newbie in this. This is the error code:

PS C:\Users\PC\Desktop> gem install pygments.rb

ERROR: While executing gem ... (Errno::EACCES) Permission denied @ rb_file_s_symlink - (vendor/pygments-main/scripts/debug_lexer.py, C:/tools/ruby23/lib/ruby/gems/ 2.3.0/gems/pygments.rb-1.1.1/vendor/pygments-main/scripts/find_error.py)

Thank you for your help.

jeudi 23 février 2017

Connect Multiple Yields in Rails

Rails Newbie. Be gentle. If I need to show more stuff I'll do it.

Trying to insert a newsletter signup block above my footer on a project but didn't make it a partial in the layouts set up.

I have the yield outputting an index from a blog.

Is it possible to have multiple yields to different indexes?

Is it possible to insert another page into a layout page?

application.html.erb

<div id="blog">
  <%= yield %>
</div>
<div>
 <%= content_for?(:newsletter) ? yield(:newsletter) : yield %>
</div>
<div>
 <%= render 'layouts/footer' %>
</div>

newsletter.html.erb

<% content_for :newsletter do %>
<h1>Get My Awesome News Letter</h1>
<p>Give me your email and keep up to date on my cat's thoughts.</p>
<%= form_tag('/emailapi/subscribe', method: "post", id: "subscribe", remote: "true") do -%>
   <%= email_field(:email, :address, {id: "email", placeholder: "email address"}) %>
   <%= submit_tag("Sign me up!") %>
<% end %>

emailapi_controller.rb

class EmailapiController < ApplicationController
def newsletter
    render params[:newsletter]
end

def subscribe
    gb = Gibbon::Request.new

    gb.lists.subscribe({
        :id => ENV["MAILCHIMP_LIST_ID"],
        :email => {:email => params[:email][:address]}
        })
end
end

routes.rb

root to: 'posts#index'

get "/:newsletter" => 'emailapi#newsletter'
post 'emailapi/subscribe' => 'emailapi#subscribe'

How to write into different tables when rails model has been inherited?

I have next models

class Building < ActiveRecord::Base;end

class Department < Building;end

class Organization < Building;end

When I create department and organization and get all departments

2.1.5 :008 > Department.all.count
(0.5ms)  SELECT COUNT(*) FROM "buildings"
=> 2 

I would like to get in this case

2.1.5 :008 > Department.all.count
(0.5ms)  SELECT COUNT(*) FROM "departments"
=> 1 

2.1.5 :008 > Organization.all.count
(0.5ms)  SELECT COUNT(*) FROM "organizations"
=> 1

2.1.5 :008 > Buildings.all.count
(0.5ms)  SELECT COUNT(*) FROM "buildings"
=> 2 

How I can do that?

INNER JOIN on a table using more than one column, rails associations

I have association in rails 3.2,

has_many :skills, :dependent => :destroy,

I wanted to add a join with a condition in the above association,

skills = user.skills.joins('INNER JOIN user_skills ON skills.id = user_skills.skill_id and skills.account_id = user_skills.account_id')

So instead of using user.skills.joins(). I only wanted to use user.skills. Scope is also one option but is it possible to add that in association.

Speech to Text with Ruby on Rails

I am an undergraduate student at the Department of Computer Science and Engineering, University of Ioannina, Greece doing my BSc thesis. I must use speech to text api (i found the open source Web Speech API from Mozilla Doundation ) and also the Ruby on Rails. My problem starts when i try to pass the text from the javascript (which translates speech to text). I found some ideas an solutions but neither was a solution to my problem. The second the html which shows the main page and make the recognition. On the second picture i show the page i was supposed to create with all the buttons i need. My problem is that when i press the "Speak" button i can not pass the Javascript result into Ruby on Rails instances/objects. The 2 textfields are rubu on rails examples to test how i can pass it to it. Please help me


enter image description here

enter image description here

How to take screenshot of googlemap from web page using PhantomJs?

My Requirement is to take screen shot of Google Map of web page.I am drawing Markers and Polyline dynamically on Google Map.I am using PhantomJS for taking screen shot.But screen shot is not capturing of complete Google Map which is displaying on web page.

Html and javascript for loading and display google map
----------
     <script>
            function initMap() {
                    var mapOptions = {
                        zoom: 15,
                        center: new google.maps.LatLng(28.5354383, 77.26393259999998)
                    };
                    var map = new google.maps.Map(document.getElementById('map'), mapOptions);
                    var project_id = $('#project').data('url')
                    var latt = substation[0]
                    var lngg = substation[1]
                    var marker = new google.maps.Marker({
                        position: new google.maps.LatLng(latt, lngg),
                        title: new google.maps.LatLng(latt, lngg).toUrlValue(6),
                        map: map,
                        draggable: true,
                        label: {
                            color: 'black',
                            fontWeight: 'bold',
                            text: "Sub-Station",
                        },
                        icon: {
                            labelOrigin: new google.maps.Point(4, 25),
                            url: '/assets/sub_station.png',
                        }
                    });
                    google.maps.event.addListener(marker, "dragend", function(event) {
                        $.getScript("/update_pole.js?project_id=" + project_id + "&Type=SS" + "&new_cordinated=" + event.latLng.toString().slice(1, -1), function(data) {});
                    });
                    var lattt = feeder[0]
                    var lnggg = feeder[1]
                    var marker = new google.maps.Marker({
                        position: new google.maps.LatLng(lattt, lnggg),
                        title: new google.maps.LatLng(lattt, lnggg).toUrlValue(6),
                        map: map,
                        draggable: true,
                        label: {
                            color: 'black',
                            fontWeight: 'bold',
                            text: "Feeder",
                        },
                        icon: {
                            labelOrigin: new google.maps.Point(4, 25),
                            url: '/assets/ptw.png',
                        }
                    });

PhantomJs for capture screenshot

var page = require('webpage').create();
  page.open('http://ift.tt/2marneo', function() {
  page.viewportSize = { width: 1440, height: 900 };
  var clipRect = page.evaluate(function(){
    return document.querySelector("div#map").getBoundingClientRect();
  });
  page.render('github.png');
  phantom.exit();
});

Expected Screen Shot

enter image description here

Currently Coming Screen Shot

enter image description here

mercredi 22 février 2017

How to write the active record query

I have three models in context of this question:

class ClearanceBatch < ActiveRecord::Base    
    has_many :items
    belongs_to :user
end

class Item < ActiveRecord::Base

  belongs_to :style
  belongs_to :user
  belongs_to :clearance_batch
  validates :id, :uniqueness => true
end

class User < ActiveRecord::Base

    has_many :items, dependent: :destroy
    has_many :clearance_batches, dependent: :destroy    
    enum role: {staff: 0, vendor: 1, admin: 2}           

end

Schema:

    create_table "clearance_batches", force: :cascade do |t|
        t.datetime "created_at"
        t.datetime "updated_at"
        t.boolean  "status",     default: false
        t.string   "boughtby",   default: ""
        t.integer  "user_id"
      end

      add_index "clearance_batches", ["user_id"], name: "index_clearance_batches_on_user_id"

      create_table "items", force: :cascade do |t|
        t.string   "size"
        t.string   "color"
        t.string   "status"
        t.decimal  "price_sold"
        t.datetime "sold_at"
        t.integer  "style_id"
        t.datetime "created_at"
        t.datetime "updated_at"
        t.integer  "clearance_batch_id"
        t.integer  "user_id"
      end



 create_table "users", force: :cascade do |t|
        t.string   "email",                  default: "", null: false
        t.string   "encrypted_password",     default: "", null: false
        t.string   "reset_password_token"
        t.datetime "reset_password_sent_at"
        t.datetime "remember_created_at"
        t.integer  "sign_in_count",          default: 0,  null: false
        t.datetime "current_sign_in_at"
        t.datetime "last_sign_in_at"
        t.string   "current_sign_in_ip"
        t.string   "last_sign_in_ip"
        t.datetime "created_at",                          null: false
        t.datetime "updated_at",                          null: false
        t.integer  "role",                   default: 0
      end

I want to find all items in a batch of the currently logged in user(mainly vendor) with the status "clearanced", and get their details in a loop from controller to my view

Can anyone please help me out with the active record query? Please! :)

The SQLite Query I think would be:

Select I.id from clearance_batches C INNER JOINS Items I on C.id = I.clearance_batch_id where C.user_id = "1" and I.status = "clearanced"

(If 1 is the current user, keeping in mind I am only allowing user of role vendors to be a user in clearance_batch table)

undefined method 'abc' for nil:NilClass

I have a method in model my_model

  def abc
    abc_mapping(column.to_s)
  end

and i am calling this method in controller

@dba = @user.method
@abc = @my_model.abc

I am calling @abc and @dba in view and it shows me the data on JSON but When i run spec i am getting error undefined method 'abc' for nil:NilClass. My unit test is verifying the data from other instance variable @dba in controller so why i am getting the error for abc method?

Rails 4 Tests running in "development" environment by default

We are porting a Rails 3 project to Rails 4. Our tests run fine under Rails 3, environment is correctly defaulted to test. However, when I switch over to my Rails 4 project and run the tests the same way...

rake test:controllers

My tests are running under development environment, wipes my dev db and output goes to development.log. I can not figure out the difference.

In my test_helper.rb I have this line...

ENV["RAILS_ENV"] = "test"

I've even tried...

Rails.env = "test"

and that does not work either.

Strange thing is, I have these puts in my test...

puts "#{__method__} Rails.env:       #{Rails.env}"
puts "#{__method__} ENV[RAILS_ENV]:  #{ENV["RAILS_ENV"]}"

and they both correctly show that I am in the "test" environment.

If I prefix RAILS_ENV=test before the rake test:controllers, all is well, but I should not have to do that.

Thank you

Devise inline errors stop showing up when overriding update method

Using Rails 3.2, Devise 3.5.1, SimpleForm

I'm using a custom update method in Devise:

def update
    resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
    resource_updated = update_resource(resource, account_update_params)
    if resource_updated
      sign_in resource_name, resource, :bypass => true
      redirect_to edit_member_registration_path, notice: "Updated successfully"
    else
      clean_up_passwords(resource)
      redirect_to edit_member_registration_path, alert: resource.errors.full_messages
    end
end

This is my form code:

<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
  <%= f.error_notification %>
  <%= f.input :first_name %>
  <%= f.input :last_name %>
<% end %>

Everything works fine, but when there are validation errors, I can't figure out why they are only showing up in the Flash message and not inline.

enter image description here


When I removed the custom update function, I get this behavior, which is exactly what I want:


enter image description here

Is there something wrong with my update function?

How to take screenshot of current whole google map screen?

Beautify, unpack or deobfuscate JavaScript and HTML, make JSON/JSONP readable, etc.

All of the source code is completely free and open, available on GitHub under MIT licence, and we have a command-line version, python library and a node package as well.

HTML , formatting: End script and style with newline? Support e4x/jsx syntax Use comma-first list style? Detect packers and obfuscators? Preserve inline braces/code blocks? Keep array indentation? Break lines on chained methods? Space before conditional: "if(x)" / "if (x)" Unescape printable chars encoded as \xNN or \uNNNN? Use JSLint-happy formatting tweaks? Indent and sections? Use a simple textarea for code input?

1

2

3

4

<div id="map"></div>

5

<script>

6

    function initMap() {

7

        var mapOptions = {

8

            zoom: 15,

9

            center: new google.maps.LatLng(28.5354383, 77.26393259999998)

10

        };

11

        var map = new google.maps.Map(document.getElementById('map'), mapOptions);

12

        var project_id = $('#project').data('url')

13

        var latt = substation[0]

14

        var lngg = substation[1]

15

        var marker = new google.maps.Marker({

16

            position: new google.maps.LatLng(latt, lngg),

17

            title: new google.maps.LatLng(latt, lngg).toUrlValue(6),

18

            map: map,

19

            draggable: true,

20

            label: {

21

                color: 'black',

22

                fontWeight: 'bold',

23

                text: "Sub-Station",

24

            },

25

            icon: {

26

                labelOrigin: new google.maps.Point(4, 25),

27

                url: '/assets/sub_station.png',

28

            }

29

        });

30

        google.maps.event.addListener(marker, "dragend", function(event) {

31

            $.getScript("/update_pole.js?project_id=" + project_id + "&Type=SS" + "&new_cordinated=" + event.latLng.toString().slice(1, -1), function(data) {});

32

        });

33

        var lattt = feeder[0]

34

        var lnggg = feeder[1]

35

        var marker = new google.maps.Marker({

36

            position: new google.maps.LatLng(lattt, lnggg),

37

            title: new google.maps.LatLng(lattt, lnggg).toUrlValue(6),

38

            map: map,

39

            draggable: true,

40

            label: {

41

                color: 'black',

42

                fontWeight: 'bold',

43

                text: "Feeder",

44

            },

45

            icon: {

46

                labelOrigin: new google.maps.Point(4, 25),

47

                url: '/assets/ptw.png',

48

            }

49

        });

50

        google.maps.event.addListener(marker, "dragend", function(event) {

51

            $.getScript("/update_pole.js?project_id=" + project_id + "&Type=Feeder" + "&new_cordinated=" + event.latLng.toString().slice(1, -1), function(data) {});

Browser extensions and other uses

A bookmarklet (drag it to your bookmarks) by Ichiro Hiroshi to see all scripts used on the page,
Chrome, in case the built-in CSS and javascript formatting isn't enough for you:
— Quick source viewer by Tomi Mickelsson (github, blog),
— Javascript and CSS Code beautifier by c7sky,
— jsbeautify-for-chrome by Tom Rix (github),
— Pretty Beautiful JavaScript by Will McSweeney
— Stackoverflow Code Beautify by Making Odd Edit Studios (github).
Firefox: Javascript deminifier by Ben Murphy, to be used together with the firebug (github),
Safari: Safari extension by Sandro Padin,
Opera: Readable JavaScript (github) by Dither,
Opera: Source extension by Deathamns,
Sublime Text 2/3: CodeFormatter, a python plugin by Avtandil Kikabidze, supports HTML, CSS, JS and a bunch of other languages,
Sublime Text 2/3: HTMLPrettify, a javascript plugin by Victor Porof,
Sublime Text 2: JsFormat, a javascript formatting plugin for this nice editor by Davis Clark,
vim: sourcebeautify.vim, a plugin by michalliu (requires node.js, V8, SpiderMonkey or cscript js engine),
vim: vim-jsbeautify, a plugin by Maksim Ryzhikov (node.js or V8 required),
Emacs: Web-beautify formatting package by Yasuyuki Oka,
Komodo IDE: Beautify-js addon by Bob de Haas (github),
C#: ghost6991 ported the javascript formatter to C#,
Go: ditashi has ported the javascript formatter to golang, 

Beautify plugin (github) by HookyQR for the Visual Studio Code IDE,
Fiddler proxy: JavaScript Formatter addon,
gEdit tips by Fabio Nagao,
Akelpad extension by Infocatcher,
Beautifier in Emacs write-up by Seth Mason,
Cloud9, a lovely IDE running in a browser, working in the node/cloud, uses jsbeautifier (github),
Devenir Hacker App, a non-free JavaScript packer for Mac,
REST Console, a request debugging tool for Chrome, beautifies JSON responses (github),
mitmproxy, a nifty SSL-capable HTTP proxy, provides pretty javascript responses (github).
wakanda, a neat IDE for web and mobile applications has a Beautifier extension (github).
Burp Suite now has a beautfier extension, thanks to Soroush Dalili,
Netbeans jsbeautify plugin by Drew Hamlett (github).
brackets-beautify-extension for Adobe Brackets by Drew Hamlett (github),
codecaddy.net, a collection of webdev-related tools, assembled by Darik Hall,
editey.com, an interesting and free Google-Drive oriented editor uses this beautifier,
a beautifier plugin for Grunt by Vishal Kadam,
SynWrite editor has a JsFormat plugin (rar, readme),
LIVEditor, a live-editing HTML/CSS/JS IDE (commercial, Windows-only) uses the library, 

Doing anything interesting? Write us to team@jsbeautifier.org so we can add your project to the list.

Written by Einar Lielmanis, maintained and evolved by Liam Newman.

We use the wonderful CodeMirror syntax highlighting editor, written by Marijn Haverbeke.

Made with a great help of Jason Diamond, Patrick Hof, Nochum Sossonko, Andreas Schneider, Dave Vasilevsky, Vital Batmanov, Ron Baldwin, Gabriel Harrison, Chris J. Shull, Mathias Bynens, Vittorio Gambaletta, Stefano Sanfilippo and Daniel Stockman.

Run the tests

How to sort of string array in ruby on rails

I am working on ruby on rails and i am new here as well ruby on rails. I am working on one project and find some issue of sorting an array of string which contains images name. I have tried many algorithm which i know doesn't help me. When i call service for image extraction it gives me like this array.

Example:

["page-1_1.png", "page-1_10.png", "page-1_11.png", "page-1_2.png", "page-1_3.png", "page-1_4.png", "page-1_5.png", "page-1_6.png", "page-1_7.png", "page-1_8.png", "page-1_9.png"]

I want to sort this array like this:

["page-1_1.png", "page-1_2.png", "page-1_3.png", "page-1_4.png", "page-1_5.png", "page-1_6.png", "page-1_7.png", "page-1_8.png", "page-1_9.png", "page-1_10.png", "page-1_11.png"]

I had tried many things to sort but can't get any solutions. please help me. Sorry for silly question

Thanks in advance :)

How can I use fields_for to update a has_many association

I am making a quiz, and I have a Survey Model, Question Model and a Choice model I am looping over all of the questions and showing the choices for that question there is also a column on the choices table for the answer they had given, which is what I am trying to update.

Here is my code.

SurveyController

def show
  @survey = Survey.find(params[:id])
end

Survey Model

class Survey < ActiveRecord::Base
  attr_accessible :name
  has_many :questions
end

Question Model

class Question < ActiveRecord::Base
  attr_accessible :question
  has_many :choices
  belongs_to :survey
end

Choice Model

class Choice < ActiveRecord::Base
  attr_accessible :name
  belongs_to :question
end

Survey Show View

<div class="modal-wrap">
  <div class="modal-header">
    <% @survey.questions.size.times do %>
      <span></span>
    <% end %>
  </div>
  <div class="modal-bodies">
    <%= form_for @survey do |form| %>
      <% @survey.questions.each.with_index(1) do |question, index| %>
        <div class="modal-body">
          <div class="title">Question <%= index %></div>
            <div class="description"><%= question.question %></div>
              <%= fields_for :choices, question.choices do |choice_fields| %>
                <%= choice_fields.text_field :name %>
              <% end %>
              <div class="text-center">
                <div class="button">Next</div>
              </div>
            </div>
          <% end %>
        <% end %>
    </div>

I can't get the form_for to work properly, can someone help me get this to work please?

mardi 21 février 2017

Rails "NOT NULL constraint failed: table.column"

I have a accounts table with not null constraint on its name and number column. I also have this piece of code for "accounts" controller in create Action:

def create
    account_number = rand.to_s[2..9]
    @account = Account.new(user_id: current_user.id, name: 'hello', number: account_number)

    respond_to do |format|
        if @account.save
            format.html { redirect_to @account, notice: "Account was successfully created.\n Your account number is: #{account_number}" }

and my "Account" model is very simple:

class Account < ApplicationRecord
    belongs_to :user

    attr_accessor :name
    attr_accessor :number
    attr_accessor :amount
end

But when I go to /accounts/new and submit, it gives me this error:

NOT NULL constraint failed: accounts.name

But why? because I have hard codded the "name" attribute with "hello" in the constructor, so why it is not filling "name" column with "hello"?

map concern hash keys with the table column

I created a concern in model

module Employee
  extend ActiveSupport::Concern

  included do
    def job
      job_hash = {
        '0': 'A',
        '1': 'B',
        '2': 'C'
       }.freeze
       job_hash[:"#{@job}"]
  end
end

I have model

class Company < ActiveRecord::Base
  self.table_name = 'Jobs'
  include Employee
end

Jobs table has column type that has values 0, 1, 2 How can i map the values from hash (0,1,2) in concern with column type and return the string value associated with it? so if the user type is 1 then return B

Thanks

Ruby on Rails: Keep check boxes selected after search

In my RoR application I have a form whereby users can search for their contacts by first name and select the ones that they want to send an email to. My problem is that after searching for say "Tom", and selecting the checkbox for "Tom", if they then reset the search to display all check boxes "Tom" is no longer selected.

Can someone please tell me how this can be sorted?

The search code is:

<% if @email.current_step == "email_recipients" %>
    <%= form_tag '/emails/contact_search', :method => 'get' do %>
      <p>
        <%= text_field_tag :search_string, params[:search_string], :placeholder => "Search by firstname" %>
        <%= submit_tag "Search" %>
      </p>
    <% end %>
<% end %>

The check boxes are displayed in a collection through the code:

<%= f.collection_check_boxes :contact_ids, @contacts, :id, :fullname %>

The controller code for the search is:

 def contact_search
    @email = Email.new(session[:email_params])
    @email.current_step == session[:email_step]
    @useraccounts = Useraccount.where(user_id: session[:user_id])
    @contacts = Contact.contact_search(params[:search_string])
    if @contacts.empty?
        flash[:notice] = "There are no emails with that subject"
        @contacts = Contact.all
    end
    render :action => "new"
 end

And in the model:

def self.contact_search(search_string)
    self.where("firstname LIKE ?", search_string)
end

I cannot work out how to keep a checkbox selected after a user then searches for something else or resets the search, can someone please shed some light on how this can be achieved?

Ruby on Rails: Why isn't my search working?

In my RoR application I am allowing users to select contacts that they want to send an email to. The users select these contacts via checkboxes on the form. I am trying to add in search functionality so that a user can search by first name and only check boxes with contacts that match that search appear.

To do this I am trying to use this code on the view:

<div class="form-group">
    <label>From Email Address</label></br>
    <% @useraccounts.each do |useraccount| %>
        <%= f.radio_button :account_id, useraccount.account_id, :checked => false %>
        <%= f.label :account_id, useraccount.account.email, :value => "true"  %><br>
    <% end %>
</div>
<div class="form-group">
    <%= form_tag '/emails/contact_search', :method => 'get' do %>
      <p>
        <%= text_field_tag :search_string, params[:search_string], :placeholder => "Search by firstname" %>
        <%= submit_tag "Search", :name => nil %>
      </p>
    <% end %>
    <label>Contacts</label></br>
    <%= f.collection_check_boxes :contact_ids, @contacts, :id, :fullname %>
</div>

Where the @contacts instance variable holds the contacts returned from the search in the controller.

When a user clicks the search button, the below controller action should be invoked.

def contact_search
    @email.recipients.build
    @useraccounts = Useraccount.where(user_id: session[:user_id])
    @contacts = Contact.contacts_search(params[:search_string])
    if @contacts.empty?
        flash.now[:alert] = "There are no contacts with that name."
        @contacts = Contact.all
    end
    render :action => "new"
end

This controller action uses the contact_search method, which is in the Contact.rb model:

def self.contact_search(search_string)
    self.where("firstname LIKE ?", search_string)
end

I also have the contact_search in the routes:

post 'emails/contact_search', :to => 'emails#contact_search'
get 'emails/contact_search', :to => 'emails#contact_search'

But for some reason, when a user clicks search they get a NoMethodError in Emails#create undefined method 'each' for nil:NilClass on the form. The error is as pictured.

enter image description here

I cannot work out why this isn't working, can someone please help?

Ruby on Rails: Search collection_check_boxes on a form

In my RoR application I have functionality that allows a user to select contacts to send an email to. I want to add to this functionality so that a user can search the contacts.

Currently, the contacts are displayed on the views/emails/form.html.erb in checkboxes that the user can select through:

<%= f.collection_check_boxes :contact_ids, Contact.where(user_id: session[:user_id]), :id, :firstname %>

Is it possible to build on this by adding a search bar above the checkboxes that allows the user to search the checkboxes by first name?

Delte server header form response

Env :- Rails 3.2 , Ruby-2.1.1p76

Server: nginx/1.8.0 + Phusion Passenger 4.0.59
X-Powered-By: Phusion Passenger 4.0.59

I want to remove these 2 headers from response. I know I can edit my nginx config and set server_tokens to off but is there any way I can handle this in codebase?

lundi 20 février 2017

Ruby on Rails validation does not show error messages for a form created with Simple_Form Gem, which is based on (MTI) Multiple Table Inheritance

My problem is a little related to this question, and the corresponding solution has proved useful and helpful, however there is a little digression from the that question which I like to explain further:

I have used active_record-acts_as gem over devise gem to create a model with multiple SignUp forms and a single SignIn Form, such that I have a Devise model called Client and other client types such as Company and Individual act as the Client Devise model, and all these MTI crafting was based on a layout different from application.html.erb layout, and I called it client_authentication_layout.html.erb

To summarize my question, I have controllers for each and every of my models with corresponding views and I did override the client devise model views such that I could render the Company and Individual forms/views as a tabbed form, which was successful.

For clarity, here are the models:

client.rb

class Client < ActiveRecord::Base
  actable
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates :email, :encrypted_password, presence: true
end

company.rb

class Company < ActiveRecord::Base
  acts_as :client

  validates :company_name,
            :company_url,
            :country,
            :contact_person,
            :phone_number,
            presence: true
end

individual.rb

class Individual < ActiveRecord::Base
  acts_as :client
end

For clarity, here is company controller:

class CompaniesController < ApplicationController


  # GET /companies/new
  def new
    @company = Company.new
  end

  # POST /companies
  # POST /companies.json
  def create
    @company = Company.new(company_params)
    if @company.save
      redirect_to root_path, notice: 'Company was successfully created.'
    else
      redirect_to new_client_registration_path
    end
  end

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

  # Never trust parameters from the scary internet, only allow the white list through.
  def company_params
    params.require(:company).permit(:company_logo, :company_name, :company_url, :country, :contact_person, :phone_number, :email, :password, :password_confirmation)
  end
end

For clarity, here are my view:

company/new.html.erb

<%= simple_form_for(Company.new) do |f| %>
  <div class="form-row">
    <%= f.input :company_name, placeholder: 'Company Name', label: false %>
    <%= f.input :company_url, placeholder: 'Company URL', label: false %>
    <%= f.input :country, placeholder: 'Country', label: false %>
    <%= f.input :contact_person, placeholder: 'Contact Person', label: false %>
    <%= f.input :phone_number, placeholder: 'Phone Number', label: false %>
    <%= f.input :email, required: true, autofocus: true, placeholder: 'Email', label: false %>
    <%= f.input :password, required: true, placeholder: 'Password', label: false %>
    <%= f.input :password_confirmation, required: true, placeholder: 'Password Confirmation', label: false %>
  </div>
  <%=    render 'shared/two_breaks' %>
  <div class='form-row'>
    <div class="col-md-12 form-group">
      <%= f.submit 'Get Started', class: 'btn btn-company' %>
    </div>
    <%=  render 'shared/four_breaks' %>
  </div>
<% end %>

individual/new.html.erb

<%= simple_form_for(Individual.new) do |f| %>

    <div class="form-inputs">
      <%= f.input :first_name, placeholder: 'First Name', label: false %>
      <%= f.input :last_name, placeholder: 'Last Name', label: false %>
      <%= f.input :about_me, placeholder: 'Type in a little details about yourself.', label: false %>
      <%= f.input :gender, placeholder: 'Choose gender', label: false %>
      <%= f.input :country, placeholder: 'Country', label: false %>
      <%= f.input :phone_number, placeholder: 'Phone Number', label: false %>
      <%= f.input :email, required: true, autofocus: true, placeholder: 'Email', label: false %>
      <%= f.input :password, required: true, placeholder: 'Password', label: false %>
      <%= f.input :password_confirmation, required: true, placeholder: 'Password Confirmation', label: false %>
    </div>
    <%=  render 'shared/two_breaks' %>
    <div class='form-row'>
      <div class="col-md-12 form-group">
        <%= f.submit 'Get Started', class: 'btn btn-individual' %>
      </div>
      <%=    render 'shared/four_breaks' %>
    </div>
<% end %>

client_authentication_layout.html.erb

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="ROBOTS" content="NOODP" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>FarFlung Jobs</title>
  <!-- /.You can include style.css into stylesheet_link_tag too. If you do so, dont forget to add style.css in asset.rb -->
  <%= stylesheet_link_tag    'clients_authentication', media: 'all' %>
  <%= javascript_include_tag 'clients_authentication' %>
  <%= csrf_meta_tags %>
</head>
<body>
  <%= yield %>
</body>
</html>

My Tabbed Form rendering Company and Individual Views on Client Devise View

<div class="container">
  <div class="row">
    <div class="col-md-6 col-md-offset-3">
      <!--col-sm-6 col-sm-offset-3 col-xs-4 col-xs-offset-3-->
      <div class="panel panel-login">
        <div class="panel-heading">
          <div class="row">
            <div class="col-xs-6 tabs">
              <a href="#" class="active" id="company-form-link"><div class="company">COMPANY</div></a>
            </div>
            <div class="col-xs-6 tabs">
              <a href="#" id="individual-form-link"><div class="individual">INDIVIDUAL</div></a>
            </div>
          </div>
        </div>
        <div class="panel-body">
          <div class="row">
            <div class="col-lg-12">
              <div id="company-form" role="form" style="display: block;">
                <h2>COMPANY</h2>
                <%= render 'companies/form' %>
              </div>
              <div id="individual-form" role="form" style="display: none;">
                <h2>INDIVIDUAL</h2>
                <%= render 'individuals/form' %>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="container">
  <div class="row">
    <div class="col-md-12 text-center">
      <span class="agreement">
        <p>By clicking Get Started, you agree to the FarFlung <a tabindex="2" href="http://ift.tt/1nBMTjM">User Agreement</a>, </p>
        <p><a tabindex="2" href="http://ift.tt/1geczMX">Privacy Policy</a>, and <a tabindex="2" href="http://ift.tt/1FRQVhm">Cookie Policy</a>.</p>
      </span>
    </div>
  </div>
</div>

Rails console

>> c = Company.new
#<Company id: nil, company_logo: nil, company_name: nil, company_url: nil, country: nil, contact_person: nil, phone_number: nil, created_at: nil, updated_at: nil>
>> c.valid?
false
>> c.errors.full_messages
["Email can't be blank", "Email can't be blank", "Password can't be blank", "Encrypted password can't be blank", "Company name can't be blank", "Company url can't be blank", "Country can't be blank", "Contact person can't be blank", "Phone number can't be blank"]
>> c.errors
#<ActiveModel::Errors:0x74f6ee0 @base=#<Company id: nil, company_logo: nil, company_name: nil, company_url: nil, country: nil, contact_person: nil, phone_number: nil, created_at: nil, updated_at: nil>, @messages={:email=>["can't be blank", "can't be blank"], :password=>["can't be blank"], :encrypted_password=>["can't be blank"], :company_name=>["can't be blank"], :company_url=>["can't be blank"], :country=>["can't be blank"], :contact_person=>["can't be blank"], :phone_number=>["can't be blank"]}>

However, if I submit an empty form, and validations takes effect, it just doesn't show on the simple_form created forms where the underlying error is.

To solve this problem, I did follow the aforementioned solution stated above, which proved successful. But it affects all other successful validating forms in other layouts of my application. Only the forms powered with client_authentication_layout.html.erb are not showing validation on the browser.

How do I solve this problem? Thanks in advance.

Permit multidimensional params

I receive this params:

<ActionController::Parameters 
  {"page_hierarchy"=>
      [<ActionController::Parameters 
          {"id"=>"6", "children"=>[
                         {"id"=>"1", "children"=>[{"id"=>"2"}, 
                         {"id"=>"5"}, 
                         {"id"=>"3"}, 
                         {"id"=>"18"}, 
                         {"id"=>"4"}]}]} permitted: false>]} permitted: false>

The page "page_hierarchy" is an array consisting of several "{id: , children: }" elements. A children as well is an array consisting of several "{id: , children: }" elements.

How can I permit params in this format?

Solutions like this one, did not work for me, because the array is multidimensional Permit array in params

Ruby form, radio buttons group name: causing an issue in accessing the value

I am working on a form which essentially saves a set of answer rows.

 def              
          answer_row_params(my_params)
                    my_params.permit(:assessment_id,:little_heart_id,:concept_id,:question_id, :answer_id)
    end
        def new
       @assessment = Assessment.find(params[:assess])
       @little_heart = LittleHeart.find(params[:little_heart])
       len = 0
       @assessment.concepts.each do |concept| 
          concept.questions.each do |question| 
          len = len + 1
       end
    end
    @answers = []
    len.times do
    @answers << AnswerRow.new
    end
    end 
    def create
        params["answer_rows"].each do |answer|
        AnswerRow.create(answer_row_params(answer))
       end
    end

If I have to explain what I am trying to achieve, I have an assessment which is assigned to a little hear(child), the assessment has multiple concepts, each concept has multiple questions and each question has 4 answers. I am trying to read assessment id, little_heart_id, concept_id, question_id and answer_id. It is going successfully till the last but one field. I am using radio buttons for answers. So the name: become "answer_rows[][answer_id]" for all the radio buttons. So this makes select only one answer among all the questions causing empty entry for the answer for all the questions except for the one chosen.

I tried making the name unique to each group of answers by doing name: "answer_rows[][answer_id][#{question.id}]". This allows selecting one answer per question. But because, the name: has something else appended to answer_rows[][answer_id], the answer is again going empty to all the fields. How can I make the names unique and still retain the way to access the answer that user has chosen?

Below is what the form looks like (I have not provided the complete view, but I believe this enough to make out what I am trying to do):

<%= form_tag answer_rows_path do %>
      <%= fields_for 'answer_rows[]', answer_row do |answer| %>
       <%= answer.hidden_field(:little_heart_id, :value => @little_heart.id) %>
            <%= answer.hidden_field(:assessment_id, :value => @assessment.id) %>

            <%= answer.hidden_field(:concept_id, :value => concept.id) %>
            <%= answer.hidden_field(:question_id, :value => question.id) %>

            <%= answer.hidden_field :answer_id%>
            <%question.answers .each do |ans| %>
                <%= answer.radio_button :answer_id, ans.id%>
            <%end%>

Rails: How to restart sidekiq before completing running tasks?

I am using sidekiq-cron for sidekiq. Now I want to restart the sidkiq after completing running task.

How can I ensure before restarting ...

Thanks

dimanche 19 février 2017

Get specific information from multi-dimensional array

Let say I have a array in this format:

[{"id":"11","children":[{"id":"9"},{"id":"5", "children":[{"id":"4"}]}]},{"id":"10","children":[{"id":"7"}]}]

And now I would like to get all ID's that are apparent in this array:

11,9,5,4,10,7

For that I would use a recursive code similar to this one:

ids = []

def find_ids arr
 arr.each do |entry|
   ids << entry["id"] if entry["id"]
   find_ids(entry["children"]) if entry["children"]
 end 
end

What would you do to get the ids?

Do you maybe know a really short version?

Thanks

avoid data type check in rails form

I have typeahead autosuggest field in my rails form for taking the name of person but in the model i have id for the person but the problem is when i create the person object and redirect to the same form its giving me an error that undefined method `person_name' for Workers Table

<%= form_for :worker, :url => {:action => :create_worker} do |f|  %>

    <%= f.text_field ("person_name"),:class => "typeahead form-control",style:"width:100%;",:placeholder=>"Enter name" , :data => {:provide => "typeahead"}%>

<%end%>

Any suggestion would be a great help

samedi 18 février 2017

replace multiple same character in string with singe character in ruby

I have a dynamically generated string which can have any number of ":" in-between them example.

example1: "test string:: this is test string"
example2: "test string:::: this is test string"

I want to convert such string into following

result string1: "test string: this is test string"
result string2: "test string: this is test string"

Please help

vendredi 17 février 2017

string containing multiple data

I have a string containing multiple numbers and each are separated by ',',as given here phone="08763843478,+918763843478,08763843478,+918763843478,+918763843478" i want it to be formatted by removing the 0 and +91. Using ruby only.

Not able to get data from collection backbone on rails

I am making an app using OMDB api. I have define a method 'top_movies' in 'movie_controller' which is rendering json data.

I have defined collection like this:

class Fanboy.Collections.Movies extends Backbone.Collection
  url: '/movie/top_movies'

Click to see JSON response

I fetched the collection in console and getting the objects in this manner.

Click to see the Image view of console

I want to display the list on a page. But I am not able to show the list.

movies_router.js.coffee

class Fanboy.Routers.Movies extends Backbone.Router
  routes:
    "": "index"

  initialize: ->
    @collection = new Fanboy.Collections.Movies()
    @collection.fetch()

  index: ->
    view = new Fanboy.Views.MoviesIndex(collection: @collection)
    $('#movies-container').html(view.render().el)

/view/movies_index.js.coffee

class Fanboy.Views.MoviesIndex extends Backbone.View
  template: JST['movies/index']

  initialize: ->
    @collection.on('reset', @render, this)

  render: ->
    $(@el).html(@template(movies: @collection))
    this

/templates/movies/movies_index.js.coffee

<h4>Top movies of all time </h4>

<ul>
  <% for movie in @movies.models : %>
    <li><%= movie.get('Title') %></li>
  <% end %>
</ul>

Here I am able to see h4 tag but not the list of Titles. What I am doing wrong here? Please someone help.

jeudi 16 février 2017

How do I implement connection pooling for Redis using Ruby?

How can I add connection pooling to my Redis setup?

for some reason I can't seem to find any information on this. I'm using redis (3.2.0) set up like so: (you can assume url is parsed ahead of this)

REDIS =  Redis.new(:host => uri.host, 
                   :port => uri.port, 
                   :password => uri.password)

Assigning ruby value to html element using jquery

I think this can be achieved easily but i am unable to know reason for not assigning a ruby variable to html element using jquery. My code looks like:

Example my ruby variable output is

@ruby_var = "1234"

I am assigning to html element using:

$("#html_element").html("<%= @ruby_var %>")

But the value is not assigning. If i use the following code every thing works fine:

var jvar = "1234"
$("#html_element").html(jvar)

Now value is assigned to html element. In my code i need to assign values to nearly 50 elements. Any help ...

going to new page sets my user_id to null in Rails

I have 2 models .. one for User(amitian) and other about They have a has_one and belongs_to association Problem is that whenever I create a new about it works fine and set my amitian_id to current_amitian but whenever I go to my new page again.. it updates my amitian_id to NULL

for eg. this is my sql after I submit the form insert into about_amitian('values' , amitian_id = 1) and if i go to new page again it says update about_amitian set amitian_id = null where about_amitian.id= 1

this is my controller and model

class AboutAmitiansController < ApplicationController

  before_action :authenticate_amitian!

  def new
    @amitian = current_amitian
  @about_amitian = @amitian.build_about_amitian
  end

  def create
    @amitian = current_amitian
    @about_amitian = @amitian.create_about_amitian(about_amitian_params)
    if @about_amitian.save
            redirect_to root_url
            flash[:notice] = 'success'
        else
            render root_url
        end
  end


private

    def about_amitian_params
    params.require(:about_amitian).permit(:dob,:interest,:bio,:catch_phrase,:relationship_status)
    end

end

and model

belongs_to :amitian 

and in amitian has_one :about_amitian

Why is it Updating my database ?

why my user_id is updated to null ? in Rails

I have 2 model one for user(amitians) other is about.rb to store their details they have a has_one relationship between them but problem is whenever I create a new about my about table has an amitan_id = null

here is my code for models

About_amitians.rb

class AboutAmitian < ApplicationRecord
 belongs_to :amitian
end

Amitian.rb

has_one :about_amitian , foreign_key: "amitian_id"

My AboutAmitian controller

def new
@about_amitian = current_amitian.build_about_amitian
  end

  def create
    @about_amitian = current_amitian.create_about_amitian!(about_amitian_params)
    if @about_amitian.save
            redirect_to :back
            flash[:notice] = 'success'
        else
            render root_url
        end

  end

private

    def about_amitian_params
    params.require(:about_amitian).permit(:dob,:interest,:bio,:catch_phrase,:relationship_status)
    end 

In my server logs I have this query

Update 'about_amitians' set 'amitian_id' = NULL where 'about_amitian'.'id'     = 1

please help. Thankyou

mercredi 15 février 2017

Filter view using gem ransack with checkbox

I should have 3 checkbox OP, SE and PM. If one or two is checked or even all three, the view will filter according to the checked values. These are employee_type and if I check OP, all employees that belong to OP type will show. I have this code using gem 'ransack' on ruby on rails

On my index.html.erb

<%= search_form_for @filter do |f| %>
    <%= f.check_box :employee_type, :value => 'OP', :id => 'checkOP' %>
    <%= f.check_box :employee_type, :value => 'SE', :id => 'checkSE' %>
    <%= f.check_box :employee_type, :value => 'PM', :id => 'checkPM' %>
    <%= f.submit 'Filter' %>
<% end %>

  <script type="text/javascript">
      $('#checkOP').on('change', function() {
          var val = this.checked ? this.value : '';
          $('#index').html(val);
      });
      $('#checkSE').on('change', function() {
          var val = this.checked ? this.value : '';
          $('#index').html(val);
      });
      $('#checkPM').on('change', function() {
          var val = this.checked ? this.value : '';
          $('#index').html(val);
      });
  </script>

On my employees_controller

  def index
    @filter = Employee.search(params[:q])
    @employees = @filter.result
  end

There shouldn't be a button since it should have filtered the moment the checkbox is checked or unchecked but I use button just to test since there's something wrong with my code that won't auto-detect if the checkbox is checked or not.

There seems to have no solution in the internet or I just couldn't find the right words to search. Any help is much appreciated.

Install ImageMagick and start your lane again error when applying icon overlay

To give some context, I am currently using a program called badge to apply an icon overlay to my app icons. Works great locally on my computer, however when I run the command badge inside an xcode bot before integration, I get the following error:

Install ImageMagick and start your lane again!

I have ran the brew update && brew install imagemagick command numerous times on the _xcsbuildd (Xcode Server) user to install ImageMagick and I still get the error. Checking the runner.rb file under the /Library/Ruby/Gems/2.0.0/gems/badge-0.7.1/lib/badgedirectory, I found the code that throws the exception. I have unanswered questions that will hopefully give me the next debugging datapoint.

1.) where does require require 'fastimage' require 'timeout' require 'mini_magick' point to in the file system? Is there any way to echo out the location when invoked so I can confirm it's in the correct directory?

2.) Looks like the runner.rb has a method named check_imagemagick! to determine if imagemagick is installed if I were to make an educated guess.. Can someone plase explain what this logic is doing?

return if `which convert`.include?('convert')
return if `which gm`.include?('gm')

Here's the full code from the runner.rb file:

require 'fastimage'
require 'timeout'
require 'mini_magick'

module Badge
  class Runner
    @@retry_count = Badge.shield_io_retries

    def run(path, options)

      check_imagemagick!
      glob = "/**/*.appiconset/*.{png,PNG}"
      glob = options[:glob] if options[:glob]

      UI.message "FP:" + glob

      UI.message "P:" + path

      app_icons = Dir.glob("#{path}#{glob}")
      UI.verbose "Verbose active...".blue
      UI.verbose "Parameters: #{options.inspect}".blue

      alpha_channel = false
      if options[:alpha_channel]
        alpha_channel = true
      end

      if app_icons.count > 0
        UI.message "Start adding badges...".green

        shield = nil
        response_error = false
        begin
          timeout = Badge.shield_io_timeout
          timeout = options[:shield_io_timeout] if options[:shield_io_timeout]
          Timeout.timeout(timeout.to_i) do
            shield = load_shield(options[:shield]) if options[:shield]
          end
        rescue Timeout::Error
          UI.error "Error loading image from shield.io timeout reached. Skipping Shield. Use --verbose for more info".red
        rescue OpenURI::HTTPError => error
          response = error.io
          UI.error "Error loading image from shield.io response Error. Skipping Shield. Use --verbose for more info".red
          UI.error response.status if $verbose
          response_error = true
        end

        if @@retry_count <= 0
          UI.error "Cannot load image from shield.io skipping it...".red
        elsif response_error
          UI.message "Waiting for #{timeout.to_i}s and retry to load image from shield.io tries remaining: #{@@retry_count}".red
          sleep timeout.to_i
          @@retry_count -= 1
          return run(path, options)
        end

        icon_changed = false
        app_icons.each do |full_path|
          icon_path = Pathname.new(full_path)
          icon = MiniMagick::Image.new(full_path)

          result = MiniMagick::Image.new(full_path)

          if !options[:no_badge]
            result = add_badge(options[:custom], options[:dark], icon, options[:alpha], alpha_channel, options[:badge_gravity])
            icon_changed = true
          end
          if shield
            result = add_shield(icon, result, shield, alpha_channel, options[:shield_gravity], options[:shield_no_resize])
            icon_changed = true
          end

          if icon_changed
            result.format "png"
            result.write full_path 
          end
        end
        if icon_changed
          UI.message "Badged \\o/!".green
        else
          UI.message "Did nothing... Enable --verbose for more info.".red
        end
      else
        UI.error "Could not find any app icons...".red
      end
    end

    def add_shield(icon, result, shield, alpha_channel, shield_gravity, shield_no_resize)
      UI.message "'#{icon.path}'"
      UI.verbose "Adding shield.io image ontop of icon".blue

      current_shield = MiniMagick::Image.open(shield.path)

      if icon.width > current_shield.width && !shield_no_resize
        current_shield.resize "#{icon.width}x#{icon.height}<"
      else
        current_shield.resize "#{icon.width}x#{icon.height}>"
      end

      result = composite(result, current_shield, alpha_channel, shield_gravity || "north")
    end

    def load_shield(shield_string)
      url = Badge.shield_base_url + Badge.shield_path + shield_string + ".png"
      file_name = shield_string + ".png"

      UI.verbose "Trying to load image from shield.io. Timeout: #{Badge.shield_io_timeout}s".blue
      UI.verbose "URL: #{url}".blue

      shield = Tempfile.new(file_name).tap do |file|
        file.binmode
        file.write(open(url).read)
        file.close
      end
    end

    def check_imagemagick!
        return if `which convert`.include?('convert')
        return if `which gm`.include?('gm')

        UI.error("You have to install ImageMagick or GraphicsMagick to use `badge`")
        UI.error("")
        UI.error("Install it using (ImageMagick):")
        UI.command("brew update && brew install imagemagick")
        UI.error("")
        UI.error("Install it using (GraphicsMagick):")
        UI.command("brew update && brew install graphicsmagick")
        UI.error("")
        UI.error("If you don't have homebrew, visit http://brew.sh")

        UI.user_error!("Install ImageMagick and start your lane again!")
    end

    def add_badge(custom_badge, dark_badge, icon, alpha_badge, alpha_channel, badge_gravity)
      UI.message "'#{icon.path}'"
      UI.verbose "Adding badge image ontop of icon".blue
      if custom_badge && File.exist?(custom_badge) # check if custom image is provided
        badge = MiniMagick::Image.open(custom_badge)
      else
        if alpha_badge
          badge = MiniMagick::Image.open(dark_badge ? Badge.alpha_dark_badge : Badge.alpha_light_badge)
        else
          badge = MiniMagick::Image.open(dark_badge ? Badge.beta_dark_badge : Badge.beta_light_badge)
        end
      end

      badge.resize "#{icon.width}x#{icon.height}"
      result = composite(icon, badge, alpha_channel, badge_gravity || "SouthEast")
    end

    def composite(image, overlay, alpha_channel, gravity)
      image.composite(overlay, 'png') do |c|
        c.compose "Over"
        c.alpha 'On' unless !alpha_channel
        c.gravity gravity
      end
    end
  end
end

I appreciate any help. Hopefully I am clear. I'm going to brush up on Ruby basics in the meantime.

Can't start rails server. I'm new.

Hi I need help and i cant even post my problem on here as i am not going to add 4 spaces to each line of code. this seems really weird. just imagine if you had over 200 lines of code. would you have to go to each line and add 4 spaces? good god. please tell me how i can post all my code and not have to add 4 spaces to each line.

here is my problem. i posted it on GitHub as i am new and didnt know this existed. so far my coding experience has been frustrating. Please assist me so I can actually learn ruby on rails.

Here is my post http://ift.tt/2lkMNEl

I am following a lynda tutorial and I cant move past the getting ruby on rails set up because of this error.

Thanks to everyone for any help I am really wanted to get this up and running

rails undefined method `[]' for nil:NilClass on association

After place a association images right after save the product, rails spitting out about method `[]' for nil:NilClass, why is showing nil, for a association already made?

  def create

  @product = current_square.products.build(params[:product])
 @images = @product.images.build
    respond_to do |format|
     format.html do
        if @product.save

params[:images]['ifoto'].each do |a|
          @images = @product.images.create!(:ifoto => a)
      end

       end
end

return numeric value in proper format and not in string

I am getting active record set from a table in model then storing the result in an instance variable in controller and simply returning all columns from json.

One of the columns data type in database is numeric(5,2). When i test it, it returns that column value in strings e.g "155"

any idea what am i missing?

Thanks

Custom styls of devise error messages display on sign-up page but don't appear on sign-in page

I made a helper_class named: devise_helper.rb:

module DeviseHelper
  def devise_error_messages!
    return '' if resource.errors.empty?

    messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
    html = <<-HTML
    <div class="alert alert-error alert-danger"> <button type="button"
    class="close" data-dismiss="alert">×</button>
      #{messages}
    </div>
    HTML

    html.html_safe
  end
end

for devise errors and made it custom style on application.css.scc and imported <%= devise_error_messages! %> inside both new.html.erb of session and new.html.erb of registration. But the problem that I have is when I test errors in sign-up page they are displayed beautifully above of my form but in sign-in page nothing happens. What is caused this problem? I also made a partial error messages:

 <% flash.each do |key, value| %>
  <div class="alert alert-<%= key %>">
    <a href="#" data-dismiss="alert" class="close">×</a>
    <ul>
      <li>
        <%= value %>
      </li>
    </ul>
  </div>
<% end %>

and rendered it in my application.html.erb

mardi 14 février 2017

How to insert data in the table without substituting the variable?

I have a rake file that create a lot of items.

namespace :db do
  namespace :seed do
    desc "items table"
      task :items=> :environment do
        Item.create(name: "first_name", process: "clean the item #{test} then pack and send to #{location}")
        ................................................
      end
  end
end

when i do rake db:seed:items I am not able to insert this data in the table without substituting the variable. Is there a way to insert this data without variable substitution so that i can substitute the variable later?

Rails how to build on iteration

After trying to save a set of images with dropzone without iteration. i switch to iterating the images and try to save on the loop. but rails spitting

ActiveRecord::StatementInvalid at /products =========================================== > SQLite3::ConstraintException: NOT NULL constraint failed: images.product_id: INSERT INTO "images" ("created_at", "ifoto", "product_data_id", "product_id", "updated_at") VALUES (?, ?, ?, ?, ?) app/controllers/products_controller.rb, line 214 ------------------------------------------------ ruby 209 210 if params[:images] && params[:images][:ifoto] 211 params[:images][:ifoto].values.each do |ifoto| 212 213 @image.ifoto = ifoto > 214 @image.save 215 216 217 end 218 render :nothing => true 219 App backtrace ------------- - app/controllers/products_controller.rb:214:in block (3 levels) in create' - app/controllers/products_controller.rb:211:inblock (2 levels) in create' - app/controllers/products_controller.rb:137:in `create' Full backtrace --

here is the dropzone code

 format.json do
     @product = current_vitrine.products.build(params[:product])
        @image =  @product.images.build(params[:images])



if params[:images] && params[:images][:ifoto]
       params[:images][:ifoto].values.each do |ifoto|

@image.ifoto = ifoto
  @image.save


                    end
    render :nothing => true

    end
  end

someone have a hint to this kind of problem?

NoMethodError in Controller#index

I am keeps on getting NoMethodError in controller index even the method is present in the model . Following is my model and controller . Please help me out where i am getting things wrong.

Controller:

    def index
      @ratings = Clerk::Rating.search(params).paginate(:per_page => 10, :page => params[:page])
    end

Model:

module Clerk
  class Rating < Base
    # Relationships
    belongs_to :application
    belongs_to :consumer

    def self.search(params)
       ratings = all
     if params[:search].present?
       ratings = ratings.joins(:consumer).where('phone like ? or lower(email) like ? or lower(first_name) like ? or lower(last_name) like ?',"%#{params[:search]}%","%#{params[:search].downcase}%","%#{params[:search].downcase}%","%#{params[:search].downcase}%")
     end
       ratings
    end
  end
end

Soft delete in rails using devise gem

Default file within registration/edit.html.erb helps us to change password as well delete current user. But i am trying to soft delete other user except current user modifying registration.erb file myself. But problem is that i could not pass proper value to satisfy condition for soft deleting user.

<%= link_to "Delete Account", registration_path(resource_name), data: {confirm: "Are you sure to delete your account?\n If you click yes your account #{current_user.email} will be deleted permanently. "}, method: :delete, :class=> "btn btn-danger" %>

It is original code to redirect towards delete, where resource_name holds id of current user i guess. So, i am welling to use same path but id of different user except current user. So can any one help me.

<table class="table table-hover">
          <thead>
          <tr class="bg-primary">
            <th>S.N.</th>
            <th>Name</th>
            <th>Email</th>
            <th>Created at</th>
            <th>Action</th>
          </tr>
          </thead>
          <% @users.each_with_index do |u, i| %>
              <tbody>
              <tr>
                <td><%= (@page.to_i - 1) * @perpage+ i+1 %></td>
                <td>
                  <% if u.first_name.present? %>
                      <%= u.first_name.slice(0, 1).capitalize + u.first_name.slice(1..-1) %>
                  <% end %>
                  <% if u.middle_name.present? %>
                      <%= u.middle_name.slice(0, 1).capitalize + u.middle_name.slice(1..-1) %>
                  <% end %>
                  <% if u.last_name.present? %>
                      <%= u.last_name.slice(0, 1).capitalize + u.last_name.slice(1..-1) %>
                  <% end %>
                </td>
                <td>
                  <%= u.email %>
                </td>
                <td>
                  <%= u.created_at %>
                </td>
                <td>
                  <a data-confirm="Are you sure to delete" rel="nofollow" data-method="delete" href="<%= user_registration_path(u) %>">
                    <span class="fa-delete">
                      <i class="fa fa-trash fa-trash-color fa-th-large fa-2x"></i>
                    </span>
                  </a>
                </td>
              </tr>
              </tbody>
          <% end %>
        </table>

This is my index page which loads all users within database. And delete button helps to delete user.

Updating static assets in public folder with Rails3 on Heroku

I have a few files in the public folder of my Rails app that aren't part of the asset pipeline (such as sitemap.xml or a .js file for an embedabble widget).

While I have no issues updating the assets in the public/assets folder, I have troubles updating these static files. Strangely, I can add new files, but I can't update existing ones. When I do update them in development, the modifications aren't taken into account on production environment (Heroku).

I have tried many things but can't seem to find a solution. Any idea ?

The route.rb doesn't point to my custom RegistrationController

i build a ruby on rails app base on dookeeper and devise and now I'm going to change the default RegistrationController that is in Devise::RegistrationsController which made by default on ruby to the custom one that i made in a folder api/users/registrationController. i tried several ways one of is this:

devise_for :users,
      only: :registrations,
      controllers: {
        registrations: 'api/users/RegistrationsController'
      }

but i get error that says this:

'api/RegistrationsController' is not a supported controller name. This can lead to potential routing problems. See http://ift.tt/ORFiAT

the ways that i declare the RegistrationController is like this:

class RegistrationsController < Devise::RegistrationsController
    respond_to :json
end

of course i made some method in like create in this file file but when i send post request like localhost:3000/users and a json file it refer me to this class class Devise::RegistrationsController < DeviseController and check whole process here.

How to Remove Mask or Corrupted Image from PDF?

I am new in programming as well as in ruby on rails.

I want to remove mask images or i can say corrupted images from extracted content and images from PDF. I have a extracted data from PDF which contains all text and images of PDF. When i display that text and images at that time it show's some bad or corrupted images. I want to remove all those images from my page.

Anyone can help me out?

Sorry for silly question.

Use Forgot Password utility in devise Rails

I am using devise for my signup process and I need to complete forgot password function. I searched on google but nothing worked. Can anyone tell me how can I send password resetting emails in devise. Thank you

lundi 13 février 2017

Export to pdf or Print a ruby source code

I have a source code written in ruby and I have to print it or export it to pdf. Is there any way of doing so it prints/exports every existing file in the application folder?

Thanks, Giovanni

How can I pass confirmation_token for devise with React and Rails

The application I'm working on is on React and Rails. I'm using devise and I wanted to add a button to resend the confirmation link.

I added it in my React js file as follows:

<a className="btn btn-secondary" onClick={this.resendConfirmation.bind(this)}>Resend Confirmation Link</a>

resendConfirmation() {
    API.get('users/confirmation', {}, function(res) {
        this.setState(res);
    }.bind(this));
}

But when I click on the button I get an error 400 Bad Request {confirmation_token: ["can't be blank"]}

Obviously it is because of the following code in my confirmations_controller.rb

def show
  resource_class.confirmation_token = User.confirmation_token
  self.resource = resource_class.confirm_by_token(params[:confirmation_token])
  if resource.errors.empty?
    # Automatically login user after confirmation.
    sign_in(resource)
    render :status => 200, :json => resource.to_json
  else
    render :status => 400, :json => {error: true, message: resource.errors.messages}
  end
end

Over here it doesn't find a confirmation_token and so it sends the 400 Bad Request.

Currently I'm storing the user's confirmation_token in the database, I wanted to know if there is any way I can sent it as a part of my request via react?