lundi 31 juillet 2017

How to send emails in Rails in production environment (heroku server)

I am using this source code to send emails in heroku server but it doesn't:

config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
  address: "smtp.gmail.com",
  port: 25,
  authentication: "plain",
  user_name: "support@gmail.com",
  password: ENV['PASSWORD'],
  enable_starttls_auto: false
}

Is there any mistake in my source code. I want to use a free way to send email in my project Thank you

Dynamic array of hashes in Sinatra

I have an array of hashes that I want to dynamically change the content on the page with. How do I show all the names of the hashes and when clicked, show the array of contacts in that particular hash?

At the moment I only have:

<% @lists.map do |list| %>
<% list.contacts.each do |contact| %>

This shows the contacts for every list, but how do I make only the selected lists' contacts show? I was thinking I could make the display to none for each container div and then when clicked, set that specific div to show - is there a more efficient way to do this?

How to call a Javascript function in rails helper

I am new to rails. I have created a helper method with a loop. Inside the loop, I want to call a javascript function. Following is the code I have written. Any help would be appreciated. Helper method

def test_helper param1
   param1.each do |x|
     "js_function(x.col1, x.col2)"
   end
end

in javascript file test.js

function js_function(x1, x2){

}

dimanche 30 juillet 2017

Couldn't find Resturant with 'id'=5

I am building this app and nested the reviews inside the restaurants. i have set all the permisions so only the users who are the owner of the review can delete their reviews. when i delete the review , the restaurant also gets deleted and i get this error Couldn't find Restaurant with 'id'=5. How can i solve that issue ? here's my code:

resturants_controller

class ResturantsController < ApplicationController
  before_action :set_resturant, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user! , except: [:index,:show]
  before_action :check_user , only: [:edit,:update,:destroy]

  # GET /resturants
  # GET /resturants.json
  def index
    @resturants = Resturant.all
  end

  # GET /resturants/1
  # GET /resturants/1.json
  def show
    @reviews = Review.where(resturant_id: @resturant.id)
      if @reviews.blank?
      @average_rating = 0
    else
      @average_rating = @reviews.average(:rating).round(2)
    end
  end

  # GET /resturants/new
  def new
    @resturant = Resturant.new
  end

  # GET /resturants/1/edit
  def edit
  end

  # POST /resturants
  # POST /resturants.json
  def create
    @resturant = Resturant.new(resturant_params)
    @resturant.user_id = current_user.id

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

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

  # DELETE /resturants/1
  # DELETE /resturants/1.json
  def destroy
    @resturant.destroy
    respond_to do |format|
      format.html { redirect_to resturants_url, notice: 'Resturant was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def resturant_params
      params.require(:resturant).permit(:name, :descirption, :website, :phone,:image)
    end

     def check_user
      unless @resturant.user = current_user
        redirect_to root_path , alert: "Sorry this Resturant belongs to someone else"
      end
    end
end

reviews_controller

class ReviewsController < ApplicationController
  before_action :set_review, only: [:edit, :update, :destroy]
  before_action :set_resturant
  before_action :authenticate_user!
  before_action :check_user, only: [:edit, :update, :destroy]



  # GET /reviews/new
  def new
    @review = Review.new
  end

  # GET /reviews/1/edit
  def edit
  end

  # POST /reviews
  # POST /reviews.json
  def create
    @review = Review.new(review_params)
    @review.user_id = current_user.id
    @review.resturant_id = @resturant.id

    respond_to do |format|
      if @review.save
        format.html { redirect_to resturant_path(@resturant), notice: 'Review was successfully created.' }
        format.json { render :show, status: :created, location: @review }
      else
        format.html { render :new }
        format.json { render json: @review.errors, status: :unprocessable_entity }
      end
    end
  end

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

  # DELETE /reviews/1
  # DELETE /reviews/1.json
  def destroy
    @review.destroy
    respond_to do |format|
      format.html { redirect_to resturant_path(@resturant), notice: 'Review was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

    def set_resturant
      @resturant = Resturant.find(params[:resturant_id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def review_params
      params.require(:review).permit(:rating, :comment)
    end

    def check_user
      unless @review.user = current_user
        redirect_to root_path , alert: "Sorry this review belongs to someone else"
      end
    end


end

resturants/show.html.erb

<div class="row">
    <div class="col-md-5">
        <p id="notice"><%= notice %></p>

   <%= image_tag @resturant.image_url %>

   <div class="star-rating" data-score= <%= @average_rating %> ></div>
   <p><%= "#{@reviews.length} reviews"%></p>
  <p>
    <strong>Name:</strong>
    <%= @resturant.name %>
  </p>


  <p>
    <strong>Descirption:</strong>
    <%= @resturant.descirption %>
  </p>

  <p>
    <strong>Website:</strong>
    <%= link_to @resturant.website, @resturant.website %>
  </p>

  <p>
    <strong>Phone:</strong>
    <%= @resturant.phone %>
  </p>



  <%= link_to "Write a review",  new_resturant_review_path(@resturant), class: "btn btn-danger"%>
  <%= link_to 'Edit', edit_resturant_path(@resturant) %> |
  <%= link_to 'Back', resturants_path %>

    </div>

    <div class="col-md-7">
     <% if @reviews.blank? %>
      <h3>No Reviews yet</h3>
   <%else%>
      <table class="table">
        <tbody>
          <% @reviews.each do |review|%>
          <tr>
            <td>
              <div class="star-rating" data-score= <%= review.rating%> ></div>
              <p><%= review.comment%></p>
              <%if user_signed_in?%>
                <%if (review.user == current_user)%>
                <%= link_to "Edit", edit_resturant_review_path(@resturant,review)%>
                <%= link_to "Delete", resturant_review_path(@resturant,review), method: :delete %>
                <%end%>
              <%end%>
            </td>
          </tr>
          <%end%>
        </tbody>
      </table>
   <%end%>
</div>


<script type="text/javascript">
  $('.star-rating').raty({
    path: 'http://ift.tt/2v9lIZZ',
    readOnly: true ,
     score: function() {
    return $(this).attr('data-score');
  }
  });
</script>

the Routes file

Rails.application.routes.draw do

  get 'pages/welcome'

  get 'pages/about'

  devise_for :users
    root 'resturants#index'
 resources :resturants do 
    resources :reviews , except: [:index,:show]
 end

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

rake routes file

                  Prefix Verb   URI Pattern                                          Controller#Action
           pages_welcome GET    /pages/welcome(.:format)                             pages#welcome
             pages_about GET    /pages/about(.:format)                               pages#about
        new_user_session GET    /users/sign_in(.:format)                             devise/sessions#new
            user_session POST   /users/sign_in(.:format)                             devise/sessions#create
    destroy_user_session DELETE /users/sign_out(.:format)                            devise/sessions#destroy
       new_user_password GET    /users/password/new(.:format)                        devise/passwords#new
      edit_user_password GET    /users/password/edit(.:format)                       devise/passwords#edit
           user_password PATCH  /users/password(.:format)                            devise/passwords#update
                         PUT    /users/password(.:format)                            devise/passwords#update
                         POST   /users/password(.:format)                            devise/passwords#create
cancel_user_registration GET    /users/cancel(.:format)                              devise/registrations#cancel
   new_user_registration GET    /users/sign_up(.:format)                             devise/registrations#new
  edit_user_registration GET    /users/edit(.:format)                                devise/registrations#edit
       user_registration PATCH  /users(.:format)                                     devise/registrations#update
                         PUT    /users(.:format)                                     devise/registrations#update
                         DELETE /users(.:format)                                     devise/registrations#destroy
                         POST   /users(.:format)                                     devise/registrations#create
                    root GET    /                                                    resturants#index
       resturant_reviews POST   /resturants/:resturant_id/reviews(.:format)          reviews#create
    new_resturant_review GET    /resturants/:resturant_id/reviews/new(.:format)      reviews#new
   edit_resturant_review GET    /resturants/:resturant_id/reviews/:id/edit(.:format) reviews#edit
        resturant_review PATCH  /resturants/:resturant_id/reviews/:id(.:format)      reviews#update
                         PUT    /resturants/:resturant_id/reviews/:id(.:format)      reviews#update
                         DELETE /resturants/:resturant_id/reviews/:id(.:format)      reviews#destroy
              resturants GET    /resturants(.:format)                                resturants#index
                         POST   /resturants(.:format)                                resturants#create
           new_resturant GET    /resturants/new(.:format)                            resturants#new
          edit_resturant GET    /resturants/:id/edit(.:format)                       resturants#edit
               resturant GET    /resturants/:id(.:format)                            resturants#show
                         PATCH  /resturants/:id(.:format)                            resturants#update
                         PUT    /resturants/:id(.:format)                            resturants#update
                         DELETE /resturants/:id(.:format)                            resturants#destroy

models/review.rb

    class Review < ApplicationRecord
        belongs_to :user , dependent: :destroy
        belongs_to :resturant , dependent: :destroy
    end

**models/resturant.rb**

class Resturant < ApplicationRecord
    mount_uploader :image, ImageUploader
    belongs_to :user, dependent: :destroy 
    validates :name , :descirption , :website , :phone , presence: true
    has_many :reviews

    validates :phone , numericality: {
        only_integer: true,
    }
end

my github repo

samedi 29 juillet 2017

Sort a list of images uploaded with carrierwave

In my application the user can upload multiple images with Carrier Wave. This images are display in a Fotorama library. So, I want to add some feature that the user can sort the list of the images how he likes.
How I am using postgreSQL with a json column like the tutorial on the docs of the gem. The path of the images are storage like this: enter image description here

I can not imagine how to do it.

The code that I am using is below:

In the form:

<%= f.file_field :imagens, multiple: true, class: "float-left" %>

In the model

class Product < ApplicationRecord
  mount_uploaders :imagens, ImagemUploader
end

The uploader is default by the gem.

It is possible to sort this?

Multiple one to many association for a single model

I have four models: Interview, Interviewee, Interviewer and InterviewDate.

The relations in terms of rails associations are as follows:

  1. An InterviewDate can have many Interviews (One to Many)
  2. An Interviewee can have many Interviews (One to Many)
  3. An Interviewer can have many Interviews and an Interview can have many Interviewers (Many to Many)

So, as you can see there are three incoming "Many" relations on the Interview model. How should the routing be done in rails given that I need to perform following tasks in the view ?

  1. List all Interviews grouped by InterviewDate

  2. Form for creation of an Interview (which would also include saving fields from other 3 tables into the database).

vendredi 28 juillet 2017

Create default value for param when not sent from Client Side in Rails

I have an application whose server-side is on Rails and the client-side is on React.

I have a situation where I allow a user to create bullet points for a TV show which they create.

These bullet points are sent as params to the Rails side but the issue is if there was a point when there is only one bullet point and then we try to delete it then it doesn't include the bullet_point state in the request.

I added this code to check if bullet point parameter exists, since the only situation it won't exist is when there are no bullet points.

if !prms.has_key?(:bullet_points)

which gives the correct boolean response.

Is there a way to reset bullet points to default in this situation?

bullet_points is an attribute of type text which has been serialized as an Array in the TVShow model

appname.herokuapp.com is redirecting me to www.appname.com after deployment

I got a project which is deployed before in evolix server with the domain name www.appname.com ( OVH domain ).

I migrate the project to heroku. After deployment when i click on the link appname.herokuapp.com it's redirected me to www.appname.com which is down as our project is no longer in evolix.

can someone explain me this issue ? and what should I do to fix it ?

I spent so much time looking for a solution but i didn't find something useful is this situation.

jeudi 27 juillet 2017

How to display two differents models in my view with will_paginate in rails?

Hi everyone I have a question , I looking for on google but I don't find an answer. I'm actually want to display Post model and User model by search in same page and for this I want to use Will_paginate to display all of them . I try this solution =>

  **require 'will_paginate/array'
  @posts =Post.search(params[:q]).order("created_at DESC")
  @users=User.search(params[:q]).order("created_at DESC")
    @all_records = (@posts + @users).paginate(:page =>params[:page], :per_page => 10)**

And In my view I want to display all query found ,so I try something like this =>

 **<%unless @posts.nil?%>
  <% @posts.each do |post| %>
  ....
**
**<% unless @users.nil?%>
<% @users.each do |user| %>
...**
<%= will_paginate @all_records %>

But it doesn't work nothing happend, so I want to know how to get @posts and @users records in @all_records to do something like this => **

<% @all_records[@posts].each do.. %>
<% @all_records[@usets].each do ..%>

** I saw some solutions that suggest to use two differentes paginate in my view like =>

**<%= will_paginate @posts %>
<%= will_paginate @users %>**

**But It's not want I want , I would'like only one paginate for all, Please Help me cause I'm going crazy, Thank you **

Devise User:edit not accepting update of subdomain | RAILS | DEVISE | devise-basecamper

So I have added a new subdomain functionality to my app that's running on heroku

gem 'devise'
gem 'devise-basecamper'

Each User has a subdomain specific for him such as: User.domain.com

Since I have old users I created a temporary functionality to let the old users add a subdomain to their user Account.

But the problem is doing that the Postgresql database is not capable of finding the user to update him:

Here's the error log here

and my application controller

class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
helper_method :subdomain, :current_account
before_filter #:validate_subdomain #, :authenticate_user!

before_action :configure_permitted_parameters, if: :devise_controller?
 before_filter :set_search

    def set_search
    @q = User.ransack(params[:q])
    @users = @q.result(distinct: true).page(params[:page]).per(10)
    end


protected

def configure_permitted_parameters
  devise_parameter_sanitizer.for(:sign_up).push(:name, :subdomain)
  devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:name, :email, :password, :current_password, :avatar, :memo, :password_confirmation, :subdomain) } #<< :name
end

private # ----------------------------------------------------

def invalidUser
    # The where clause is assuming you are using Mongoid, change appropriately
    # for ActiveRecord or a different supported ORM.
    #@current_user ||= Association.where(subdomain: subdomain).first
    User.where("subdomain = ?", subdomain).first
end

def invalidsubdomain
    case subdomain
        when 'www', '', nil
          false
        else
          true
    end
end 

def subdomain
    request.subdomain
end

# This will redirect the user to your 404 page if the account can not be found
# based on the subdomain.  You can change this to whatever best fits your
# application.
def validate_subdomain
        if (invalidUser.nil? && invalidsubdomain)
            redirect_to '/404.html' 
        end             
end

end 

And my routes.rb

Rails.application.routes.draw do


get '/confessions/:id',     to: 'users#index',       via: 'get'
resources :confessions

devise_for :users, :controllers => { :omniauth_callbacks => 
"users/omniauth_callbacks" ,:registrations => "users/registrations" }


 resources :users, :only => [:index, :show]

 constraints(Subdomain) do
 match '/' => 'users#show' , via: 'get'
 end

 root to: 'pages#index'
 match '/users',   to: 'users#index',   via: 'get'
 match '/users/:id',     to: 'users#show',       via: 'get'

 get '/myconfessions', to: 'pages#myconfessions', as: :myconfessions
 get '/search', to: 'pages#search', as: :search

 end

And finally my lib/subdomain.rb

class Subdomain
  def self.matches?(request)
    case request.subdomain
    when 'www', '', nil
      false
    else
      true
    end
  end
end

Thank you prior! any help would be wonderful. I've been stuck on this for a while

how to create new action for listing all data while i am already used show controller

This is my jobs controller

def index
  @job = Job.new
end
def create
  @job = Job.new(job_params)
 if @job.save
  flash[:notice] = "resume is uploaded"
  redirect_to @job
 else
  flash[:notice] = "resume is not uploaded"
  redirect_to blogs_path
 end
end

def list
  @jobs = Job.all
end
def messages
 @pages = Page.all
end
def show
 @job = Job.find(params[:id]) 
end
def new
 @post = Post.new
end    

My error is if i will search jobs/list,it will take list is a id.that means id='list'.why it does not take the list is action.

my confif/routes.rb resources :jobs do collection do get ':list' :as => 'list' end end

This also i added but is not working

get 'jobs/list'

Capistrano 3: After deployment is not "refreshed" code (website stays as prior the deploy)

I was doing some modification on the website (pure HTML+CSS), deployed it on the server and after refreshing the browser the content was the same.

So I logged in on the server, killed unicorn, started it manually and the new content finally appeared.

How do I do this automatically?

Currently, I have this deploy.rb setup:

# config valid only for current version of Capistrano
lock "3.8.1"

set :application, "project"
set :repo_url, "git@bitbucket.org:username/project.git"
set :branch, "master"
set :tmp_dir, '/home/deployer/tmp'

set :deploy_to, "/home/deployer/apps/project"
set :keep_releases, 5

set(:executable_config_files, %w(
  unicorn_init.sh
))

# files which need to be symlinked to other parts of the
# filesystem. For example nginx virtualhosts, log rotation
# init scripts etc.
set(:symlinks, [
  {
    source: "nginx.conf",
    link: "/etc/nginx/sites-enabled/default"
  },
  {
    source: "unicorn_init.sh",
    link: "/etc/init.d/unicorn_#{fetch(:application)}"
  },
  {
    source: "log_rotation",
   link: "/etc/logrotate.d/#{fetch(:application)}"
  },
  {
    source: "monit",
    link: "/etc/monit/conf.d/#{fetch(:application)}.conf"
  }
])


namespace :deploy do   
  desc 'Restart application'
  task :restart do
    task :restart do
      invoke 'unicorn:reload'
    end
  end
  after :publishing, :restart    

  desc "Make sure local git is in sync with remote."
  task :check_revision do
    on roles(:web) do
      unless `git rev-parse HEAD` == `git rev-parse origin/master`
        puts "WARNING: HEAD is not the same as origin/master"
        puts "Run `git push` to sync changes."
        exit
      end
    end
  end
  before "deploy", "deploy:check_revision"
end

What do I need to add yet in order to don't need to manually restart server?

Thank you

mercredi 26 juillet 2017

How to use srtftime in views

Hi I am getting an error with strftime.

My views look like

<%=room.date%> works and yields "2017-07-27".

However I want to convert this to July 27, 2017.

<%= Date.parse(room.date).strftime("%B %e, %Y ") %> Does not work and causes the following error: ActionView::Template::Error (no implicit conversion of Date into String):

My schema has

t.date     "date"

I don't know what I am doing wrong. Thanks!

Adapter Pattern in ruby

I know what is adapter(theoretically),but i do not know how to implement in ruby.How to implement the adapter pattern,when adaptor is inheriting target .There are few doubts:

  1. How we can able to pass the newly generated object of adaptee to adaptor.
  2. How adaptor will use the object of target to generate an object containing the data of adaptee .

Please provide an example. Thank you!!

How to query rails way ? Rails 3.2

List of relationship between models:

class ErrorScope  < ActiveRecord::Base
  belongs_to :server
  has_many :scope_to_fixflow_map
  attr_accessible :id, :server_id, :error_codes, :scoping_method, :priority, :error_codes_is_wildcard_match
  serialize :error_codes
  .....
end

class ScopeToFixflowMap < ActiveRecord::Base
  belongs_to :error_scope
  attr_accessible :id, :server_id, :error_scope_id, :path, :fixflow_class_name
  ......
end

class Server < ActiveRecord::Base
  has_many :error_scopes 
  ......
end

Now i have a sql query which gives me desired output:

SELECT fixflow_class_name 
FROM error_scopes s
join scope_to_fixflow_maps m on s.id=m.error_scope_id
join servers serv on serv.id=s.server_id
where error_codes regexp 'error_scope_test'
and path = 'x'
and assettag = 'y'

What I tried so far. It works

ErrorScope.where("error_codes like ?", "%error_scope_test\n%").select {|tag| tag.server.assettag == "y"}[0].scope_to_fixflow_map.select {|y| y.path == "x"}[0].fixflow_class_name

using joins

ErrorScope.joins(:server, :scope_to_fixflow_map).where("error_codes LIKE ?", "%error_scope_test%").select {|tag| tag.server.assettag == "y"}[0].scope_to_fixflow_map.select {|y| y.path == "x"}[0].fixflow_class_name

I am sure there must be better way to do this query??

factory error in raills

An error occurred in a before(:suite) hook. Failure/Error: FactoryGirl.lint

FactoryGirl::InvalidFactoryError: The following factories are invalid:

  • invoice - nil can't be coerced into Fixnum (TypeError)
  • paid_invoice - nil can't be coerced into Fixnum (TypeError)
  • receipt - nil can't be coerced into Fixnum (TypeError)
  • refund_receipt - nil can't be coerced into Fixnum (TypeError)

    /usr/local/rvm/gems/ruby-2.3.0@carve/gems/factory_girl-4.8.0/lib/factory_girl/linter.rb:12:in `lint!'

/usr/local/rvm/gems/ruby-2.3.0@carve/gems/factory_girl-4.8.0/lib/factory_girl.rb:67:in `lint'

./spec/support/factory_girl.rb:13:in `block (2 levels) in '

Finished in 4.11 seconds (files took 3.05 seconds to load) 0 examples, 0 failures, 1 error occurred outside of examples

mardi 25 juillet 2017

Best way to get records from another model again and again - Rails

I have a model Booking which contains space_id attributes associated with Space Model by belongs_to :space.

Now I have multiple spaces and want to count each booking with respect to every id.

I want to get the best way to fatch records from DB without fire query again and again. Currently, I'm doing like this:

spaces = Space.all
result = []
spaces.each do |s|
    result << s.as_json.merge(:bookings_counts=>s.bookings.count)
end

but this is firing query again and again form db. is there any best way to do this?

Ruby: list file names with special characters

I have a file as data/raw/sample�X�}.pdf. The file has special characters .

Now when I try to run the below code to list the file:

Dir["data/raw/*"]

It gives below output:

["data/raw/sample\357\277\275X\357\277\275}.pdf"]

i.e the special characters like � are getting converted to some octal representation like \357 . I want a ruby code that lists the exact file with special characters.

lundi 24 juillet 2017

How to turn off server signature + heroku + ruby on rails

I have one page site and deployed on heroku. While checking SEO, I found that Server Signature is On. So How can I turn off this ?

can i combine two routes into one for same controller

I have two routes for two actions in same controller as below. is this the right way or is there a way to call them together since they are in same controller?

resources :abc, only: [] do
get 'help', controller: 'my_controller', on: :collection
get 'update', controller: 'my_controller', on: :collection

Devise redirect path after sing-up and before confirmation

I have implemented the devise gem on my app and I want to redirect to a specific path after sign_up. I have this method in the registration_controller.rb but its does not work, it redirects to the root path instead of the specified path. I also have devise :confirmable set up but I'm delaying the sent confirmation email until later.

def after_sign_up_path_for(resource)
  new_transaction_path(session[:registration_params])
end

And returns the following flash notice: translation missing: en.devise.registrations.store.signed_up_but

How can I make this work?

dimanche 23 juillet 2017

Images are not retrieving on error

I am storing multiple images using the nested fields for. If we upload invalid image, then the form throws error and uploaded image is not displaying in the failed scenario I am expecting the attached images should be retried on the error page. with params I feel bit difficult to dispay..please guide Here is the params:

{"utf8"=>"✓", "authenticity_token"=>"nW68WIcgezcLa9pSBRL5iX2ABAePxLUTmbpX8xZgG2U=", "package"=>{"id"=>"32", "title"=>"sfsd", "description"=>"", "prerequisite"=>"", "report"=>"", "pay"=>["1"], "collect"=>"0", "report_type"=>"1", "is_popular"=>"0", "images_attributes"=>{"0"=>{"avatar"=>#<ActionDispatch::Http::UploadedFile:0x0000000547bd28 @tempfile=#<Tempfile:/tmp/RackMultipart20170724-4334-uxkvt9>, @original_filename="download.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"package[indicator_images_attributes][0][avatar]\"; filename=\"download.jpg\"\r\nContent-Type: image/jpeg\r\n">}}}, "test_panel_or_profile_id"=>"", "commit"=>"Next"}

Running Ruby On Rails "RubyMine" Array values in the parameter to `Gem.paths=` are deprecated

Ruby on rails, i have a problem every time i'm trying to run the project on RubyMine it gives me this error : Array values in the parameter to Gem.paths= are deprecated. Please use a String or nil. An Array ({"GEM_PATH"=>["C:/Ruby24-x64/lib/ruby/gems/2.4.0", "C:/Users/AM/.gem/ruby/2.4.0"]}) was passed in from D:/Projects/Ruby-on-Rails-4-Getting-Started-master/bin/rails:3:in load' C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/bundler-1.15.2/lib/bundler/spec_set.rb:87:inblock in materialize': Could not find json-1.8.3 in any of the sources (Bundler::GemNotFound), and i've tried almost all the solutions available ??

samedi 22 juillet 2017

uninitialized constant API::V1::MusicController

Im realy sorry to ask this when there are a lot of similar posts but none seams to work for me.

/app/controllers/api/v1

class Api::V1::MusicsController < ApplicationController
    def index
      articles = Article.order('created_at DESC');
      render json: {status: 'SUCCESS', message:'Loaded articles', data:articles},status: :ok
    end
end

routes.rb

Rails.application.routes.draw do

  namespace 'api' do
    namespace 'v1' do
      resources :music
    end
  end 

end

Ruby - Count comment

I want to count the number of comment on my page called view

here is my controler code

  def view
    @gallery = Gallery.find_by!(id: params[:id]).decorate
    @comments = Comment.select(:user_id, :description).includes(:user).where(gallery_id: @gallery.id)
    if user_signed_in?
      @like = current_user.likes.where(gallery_id: @gallery.id).first
    end
  end

this is view page

  .text-container
    p: strong Komentar
    - @comments.each do |comment|
      = render :partial => comment
      .media.testimoni-box
        .col-md-12.jaminan
          .media-heading.strong = comment.user_personal_name
          = comment.description
    ---->I want to show the number of comment here

Please help me. and thanks for advance

Is there any alternative of Heroku for ruby on rails app to deploy live?

I wanted to deploy my ruby on rails app live I already try Herkou & Aws. So is there any alternative of this?

vendredi 21 juillet 2017

while running selenium script in ruby i want to give a alert of every task how to give annotations

while running selenium script in ruby i want to give a alert of every task how to give annotations.

in selenium script I have login and create user and set role and logout is there,

while login alert should be login

after create user alert user created

I m running selenium script by using ruby another app

jeudi 20 juillet 2017

how i Do functionality of add/remove cart for e-commerce web application in rails without any gem

i have product model, user model and Cart model. in cart model there is a two references 1. user_id , 2.product_id.

Keep namespacing of a controller when including a model in Rails

I am trying to keep the namespace of a class when including a module. Lets say I have these Models:

class Shop < ApplicationRecord
  self.abstract_class = true
end
class A::Shop < ::Shop
end
class B::Shop < ::Shop
end

And this controller:

module A
  class ShopController < AuthenticatedController
    include Basic::Features
    def test
      p Shop.new #YES! its a A::Shop 
    end
  end
end

And this Module:

module Basic
  module Features
    def test
      p Shop.new  #Shop (abstract)
    end
  end
end

In the above example, the namespace is overwritten when including the module. As I want to use the Basic::Features module at multiple places in my codebase, I would like to automatically switch between A::Shop and B::Shop when including it in the controller.

Anybody any idea if this is possible, and how.

Rails how to organize views

I have one app with two different views per controller

So i want to have http://ift.tt/2uCL5TX

Should be rendered old templates

At http://ift.tt/2ubTdYT renders new templates

I think i need to do it through params in application controller?

or maybe http://ift.tt/2uC9KIg or old

How to do it?

rake db:migrate doesnt work after paperclip gem is installed

Hello guys im coding an instagram like app on rails, after i installed the paperclip gem (5.1) i created a model that i must migrate in the db. as i mentioned in the title the rake db:migrate doesnt work. i tried restarting the rails server and my laptop as suggested by some solutions, also tried adding the [5.1] next to the ActiveRecord::Migration like this as others suggested.

class CreatePics < ActiveRecord::Migration[5.1]

after changing some versions it still doesnt work. if its helpful the code project lies here http://ift.tt/2vmEN8a

the error i get is

rake db:migrate --trace
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Invoke db:load_config (first_time)
** Execute db:load_config
** Execute db:migrate
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

Directly inheriting from ActiveRecord::Migration is not supported. Please specify the Rails release the migration was written for:

  class AddAttachmentImageToPics < ActiveRecord::Migration[4.2]
/Users/leonidas/.rvm/gems/ruby-2.4.0/gems/activerecord-5.1.2/lib/active_record/migration.rb:525:in `inherited'
/Users/leonidas/Desktop/Instagramm/db/migrate/20170719181859_add_attachment_image_to_pics.rb:1:in `<top (required)>'
/Users/leonidas/.rvm/gems/ruby-2.4.0/gems/activesupport-5.1.2/lib/active_support/dependencies.rb:292:in `require'

and goes on and on like this

mercredi 19 juillet 2017

How to reload the model when using this.get('store').query?

I have a user model with attributes name and city, i am fetching 25 records at a time from server since there are lot of user records

so my routes has this

model(){
return this.get('store').query('user', {page:1}); }

which fetches me the first 25 records

Now in my template i have a button which on click hits the action to fetch the next 25 records ie

action:{
findMoreUsers(){
        this.get('store').query('user', {page:2});
    } }

Now in the browser, in the ember data the new records are loaded ie it shows 50 records

but when i try to do something like this.get('model'), it gives me the only the old records but not the newly loaded records

So how to to refersh the model so that it shows me all the old as well as new records(50 records)?

Thanks

after upgrading RSpec to version 3 I can't run single spec file anymore

We are in the process of upgrading rails from 3.4 to 4.2. When we upgraded the rspec to the latest version, even after forcing the rspec to run only one spec it runs around 900 tests but my file only hast two contexts. I use something similar to this command :

rspec spec/myfile_spec.rb

What can be wrong? Is it something that I can fix in spec_helper? I d

AWS Console inside RoR Web application

Will appreciate if anyone can give suggestion,

I want to show AWS EC2 console right inside my RubyOnRails or Angular.js application, so that user can access the server console directly from the application. Like what tutorials point and several other websites are providing like below, http://ift.tt/2vBOYFw [Here, Ruby console is available]

Thanks in Advance.

How to bind localhost RoR app to discourse docker container?

I've a ruby on rails app which is on 0.0.0.0:3000 and discourse docker container on port 0.0.0.0:80 . I want to bind localhost RoR app with docker container because postgreSQL is running inside the docker container and want to connect RoR app with postgreSQL which is inside docker container. How can I make db connection between RoR app and docker container postgrePSQL.

Here is my RoR controller.

class CronController < ApplicationController

    # slack channel hook
    $slackHook = "http://ift.tt/2uBsszh"
    $discourseHost = 'community.cloudways.com/';
    $messageText = "New Notification";

    # import http module
    require 'net/http'

=begin
    A method which build connection with postgreSQL and fetch last 24hr records 
=end

    def slackNotification
        logger.debug "*******Cron Started********"
        begin
            $query = "SELECT users.username AS username, topics.title AS topic_title, topics.id AS topic_id, posts.raw AS raw FROM post_replies 
                JOIN posts ON posts.id = post_replies.post_id 
                JOIN users ON users.id = posts.user_id 
                JOIN topics ON topics.user_id = users.id
                WHERE post_replies.created_at BETWEEN current_date AND current_date - INTERVAL '1' DAY;"
            $res = ActiveRecord::Base.connection.exec_query(query);

            # iteration on each record
            $res.each do |row|
                sendNotifications row
            end

            logger.debug "*******Cron successfully executed.********"
            render :json => {:status => "true", :message => "Cron successfully executed."}

        rescue Exception => e
            logger.fatal "Exception: #{e}"
        end
    end

=begin
    such method which take payload and send it to slack hook url
    @params row
=end
    def sendNotifications row
        $title = row['topic_title']
        $topicId = row['topic_id']
        $content = row['raw']
        begin
            uri = URI.parse($slackHook)
            # Full control
            http = Net::HTTP.new(uri.host, uri.port)
            response = Net::HTTP.post_form(uri, {
                'payload' => '{
                    "fallback": "#{$messageText}",
                    "text": "#{$title}",
                    "pretext": "<http://#{$discourseHost}|#{$title}>",
                    "color": "#36a64f",
                    "fields": [
                        {
                            "title": "#{$title}" , 
                            "value": "#{$content}",
                            "short": false 
                        }
                    ]
                }'
            })
        rescue Exception => e
            logger.fatal " Attributes: title: #{$title}, topicId: #{$topicId}, content: #{$content}, URL: <http://#{$discourseHost}|#{$title}> "
            logger.fatal "Exception: #{e}"
        end
    end
end

mardi 18 juillet 2017

Rspec for controller

def finding
  if params[:called_by] == ‘ATTACHMENT’
    Dir.mkdir('tmp/tmp_pdf') unless File.exists?('tmp/tmp_pdf')
    name = params[:ticket_attachment].original_filename
 end 
end

Above is my controller method.

it 'called attachment' do
    get :notifications, params: { id: users.user_id, called_by:'ATTACHMENT'}
    expect(response).to render_template(:finding) 

end

Above is my Spec for the Controller method.

on Running my spec , i am getting the error as

NoMethodError:
   undefined method `original_filename' for nil:NilClass

Looking forward for the solution, thanks in advance.

lundi 17 juillet 2017

Ruby on rails database not working

I am going through the 'Installing and Running ruby on Rails 5: Windows' tutorial on lynda. I got the MySQL database up and running and rail installed correctly. After configuring my SQL database with my project, to test it I entered the command 'rails db:schema:dump'. I got the following error:

Failed to load libmysql.dll from C:\Ruby24-x64\lib\ruby\gems\2.4.0\gems\mysql2-0.4.8-x64-mingw32\vendor\libmysql.dll

I checked file explorer and saw that the file does indeed exist. So why is it not loading properly?

/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' -- while trying to start the server

I end up with this error - /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in 'require'

I am using a vagrant environment and this is the flow of executing the commands

vagrant up
vagrant ssh
cd /vagrant/
bundle
rake db:create
rake db:migrate
rspec spec //for the tests

and rails s for running it.

dimanche 16 juillet 2017

changed? depreaction Rails 5.1.2

Devise before it saves the record, it checks if attributes changed and if so it performs special actions:

def send_devise_notification(notification, *args)
  # If the record is new or changed then delay the
  # delivery until the after_commit callback otherwise
  # send now because after_commit will not be called.

  if new_record? || changed?
    pending_notifications << [notification, args]
  else
    # Devise: send emails with background job
    devise_mailer.send(notification, self, *args).deliver_later
  end
end

http://ift.tt/2v65vlG

The following line gives me an depreaction now:

if new_record? || changed? 

DEPRECATION WARNING: The behavior of 'changed?' inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after 'save' returned (e.g. the opposite of what it returns now). To maintain the current behavior, use 'saved_changes?' instead.

When I use saved_changes? instead of changed? the code won't work correctly anymore, because in this step the record is not yet saved

e.g.

user.email = "hello@example.com"
user.changed? => true
user.saved_changes? => false

Which method should I use instead? How can I prevent the depreaction warning? Thanks

vendredi 14 juillet 2017

Rails Exception Notifier does not send mail on 404

I could request a page that does not exists and I would suppose a 404 would be send, but with the configuration below I receive mails for other errors but not for 404.

What could I do?

Rails.application.config.middleware.use ExceptionNotification::Rack,
  :ignore_crawlers => %w{Googlebot bingbot},
  :ignore_cascade_pass=>false,
  :email => {
    :email_prefix => "[Exception] ",
    :sender_address => %{" Production" <mail@example.com>},
    :exception_recipients => %w{mail2@example.com}
  }

Ruby on Rails resque task gets error

I'm trying to use resque in my ruby on rails application.

I created resque.rake file in lib/tasks folder

require 'resque/tasks'

task 'resque:setup' => :environment

I've started redis server by following line

redis-server /usr/local/etc/redis.conf

I have this RakeFile in my application:

require_relative 'config/application'

Rails.application.load_tasks

But when I run the following command to start rake

rake resque:work QUEUE='*'

I'm getting this error:

LoadError: cannot load such file -- resque/tasks

I can't see What I'm missing,

Any suggestions ?

Thanks.

Note: I'm using rails 5.0.1

How do I deploy Ruby on Rails remotely connected a Cassandra database in Docker?

How do I deploy Ruby on Rails remotely connected a Cassandra database in Docker? Can any one help me on this?

rake db:create works, rails dbconsole works, rake db:migrate/db:seed/test fail

When I try to use a rake task that isn't rake db:create that uses a DB connection (ie rake db:migrate) Connection refused - sendto(2) for "127.0.0.1" port 9999

Inexplicably, it tries to connect on non-default port (9999) that, as far as I can tell, not in the config (ie config/database.yaml) . When I change MySQL to use this port, I get a slightly different error: Mysql2::Error: Can't connect to MySQL server on '127.0.0.1' (61)

MySQL server is a vanilla homebrew install, if that matters (whole thing is running on MacOS 10.12.3)

Rails console issue with attr_encrypted

I am using rails attr_encrypted gem for encrypting data before storing in database. It works fine on my application as it encrypts with the provided key and decrypts it using the same key via my application. But when I create a instance with my rails console, it does not encrypt with the key that is provided in the application ( uses some random key each time maybe) and hence I am not able to decrypt it when I see that instance in my application.

Below picture shows that if I create the user with the same name twice in console, each time the encrypted data is different. I am following the tutorial on this page enter image description here

When I try to access the page on my application, the user made by console are showing this errorenter image description here

Ruby on Rails API + Devise

I'm working with a friend on a projet with RoR + Devise for authentication.

My friend is doing an application with React Native.

I'm actually trying to build with my existing RoR project an API.

  namespace :api do
    namespace :v1 do
      # Users
      get '/users' => 'users#index'
      get '/users/:id' => 'users#show'
    end
  end

  # BaseController
  class Api::V1::BaseController < ApplicationController

  protect_from_forgery with: :null_session
  before_action :destroy_session

  rescue_from ActiveRecord::RecordNotFound, with: :not_found!

  def destroy_session
    request.session_options[:skip] = true
  end

  def not_found!
    return api_error(status: 404, errors: 'Not found')
  end

  def api_error(status: 500, errors: [])
    unless Rails.env.production?
      puts errors.full_messages if errors.respond_to? :full_messages
    end
    head status: status and return if errors.empty?

    render json: jsonapi_format(errors).to_json, status: status
  end
end

# UsersController
class Api::V1::UsersController < Api::V1::BaseController

  before_action :find_user, only: [:show]

  def index
    @users = User.all
    render json: @users
  end

  def show
    render json: @user
  end

  private
  def find_user
    @user = User.find(params[:id])
  end

  def user_params
    params.require(:user).permit(:username, :email, :password)
  end
end

I configured my Serializers too.

My question is :

How can i handle with Devise and API configuration, registrations / sessions controllers ?

before_destroy check if attribute for related model is given (version control)

i have a model which has_many relation to a version model. Any action on the parent model need to be tracked. At the form for delete i have added a nested form to enter a ticket number which will be added to the versions. How could i check in the model validations if the ticket is given? I will write the version before the destroy on the model is called.

# model.rb
class Model < ActiveRecord::Base
      has_many    :versions,
                  :as => :version_object
end

# models_controller.rb
def destroy                                             
    @model = Model.find(params[:id])                 
    self.write_versions('Destroy')                        
    @Model.destroy                                     

    respond_to do |format|                                
      ...
    end                                                   
  end

# delete.html.erb
<%= form_for [@model.parent_object, @model], :html => { :class => 'form-horizontal' }, :method => :delete
    do |f| %>
      <div class="form-actions">
        <%= f.fields_for :versions, @model.versions.build do |v| %>
          <%= v.text_field :ticket, {:class => 'text_field', :placeholder => 'Ticket Nummer'}%>
        <% end %>
        <%= f.submit 'Delete Model', :class => 'btn btn-danger' %>
        <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
                    :back, :class => 'btn' %>
      </div>
    <% end %>

I already tried to implement a before_destroy method to check if a version with the 'Destroy' action is written but this won't work because the key fields to identify the certain action could be exist more than one time. The versions are incremental and can be rolled back step by step to get an older version and my model could have more than one relation identifier at the lifetime of his parent.

An solution would be to check the existence of the ticket at the controller through the params, but validations should be at the model.

I don't want to use a versioning gem.

Anybody a hint how to implement such a validation?

jeudi 13 juillet 2017

Where to ask 'best-practice'

Sometimes I need some consultations on ruby/rails/smth_else best practices or just smth like 'am I doing right?' I know it's no good to place them here, so I wonder if there are some sources on the Internet where I can ask such a question?

Change date with offset value to UTC. Ruby

I have this date that which is in timezone offset format that I need to convert to UTC format. For example:

date1 = 2017-07-13T17:13:12-04:00

date2_utc = 2017-07-13 21:13:12 UTC

I need to compare if those two date are same date. Or If I can convert date1 to UTC then i can compare those two.

How create files inside backbone assets

I want to create files inside backbone collection, template and model using one commend like "scaffold". My directory structure is as follow. How it will createenter image description here

mercredi 12 juillet 2017

Why does Ruby fail to remove method even though it is clearly defined?

I work on a rather complex Ruby project that has multiple interdependencies. With recent bundle update, I got logging-rails (0.6.0) pulled in, and that's where mystery started. Attempts to load the project failed, and I tracked them down to this line in that newly updated gem failing with an error:

    NameError: method `logger' not defined in ActionView::Base

OK, I thought, so logger methis not defined somehow, let's figure out why. I opened the logging-rails code in editor and added some debug output before problematic line. But after I ran the project again, I got really puzzled with the results it yielded. Namely:

    puts "#{LOGGER_METHOD.inspect} is included: #{ other.instance_methods.include?(LOGGER_METHOD)}"
    => 
    :logger is included: true

    puts other.method(:logger).source_location.inspect
    =>
    ["/CENSORED/.bundle/gems/ruby/2.3.0/gems/actionpack-3.2.22.5/lib/action_view/base.rb", 149]

    puts other.method(:logger).inspect
    =>
    #<Method: ActionView::Base.logger>

And ultimately:

    result = nil
    begin
      ActionView::Base.logger
      result = "success"
    rescue
      result = "failure"
    end
    puts result

    => 
    success

I'm at a total loss now. The method is defined; Ruby knows exactly where; it executes just fine and returns a result; but when it comes to undefining the method, it's suddenly not defined? WTF?..

mysql,sql,ruby,rails,html [on hold]

I have to draw a pie chart which takes the data from mysql and I am working on ruby on rails. Can you explain it to me step by step? I should draw it with both chartkick and highcharts.

Rest client post request, error with multipart

I have the following ajax request which works fine, but when i try the same through rest-client ruby gem i'm getting the following error

"{\"error\":{\"message\":\"Wrong request body. Check if all parameters set correctly\",\"code\":401},\"cartItems\":[]}"

JS:

    dataContentType = 'application/json'
    data = new FormData
    if dataContentType == 'text/xml'
      data.append 'data', new Blob([ $('#requestXml').val() ], type: 'text/xml')
    else
      data.append 'data', new Blob([ $('#requestJson').val() ], type: 'application/json')
      console.log('requestJson', $('#requestJson').val())
    fileIdx = 0
    $('input[type=file]').each (i, value) ->
      `var i`
      i = 0
      while i < value.files.length
        data.append 'file[' + fileIdx + ']', new Blob([ value.files[i] ], type: 'application/octet-stream'), value.files[i].name
        fileIdx++
        i++
      return
    $.ajax
      type: 'POST'
      url: 'http://ift.tt/2u8jwRV'
      data: data
      cache: false
      contentType: false
      processData: false
      beforeSend: (request) ->
        request.setRequestHeader 'Accept', dataContentType
        return
      dataType: 'text'
      success: (data, textStatus, jqXHR) ->

data variable contains this

{"currency":"USD","cartItems":[{"toolID":"toolID","MyCartItemReference":"some reference","modelID":"modelID","modelFileName":"","fileUnits":"mm","fileScaleFactor":"1","materialID":"00e005a8-b29b-4196-ba4e-57ac1c4ce60c","finishID":"bba2bebb-8895-4049-aeb0-ab651cee2597","quantity":"1","xDimMm":81.266,"yDimMm":159.935,"zDimMm":10.096,"volumeCm3":15.5864,"surfaceCm2":260.288,"iMatAPIPrice":"25.0","mySalesPrice":"26.0"}]}

I tried with the following using rest client

request = RestClient.post("http://ift.tt/2u8jwRV",{:currency => "USD",:cartItems => [{:toolID => "toolID",:MyCartItemReference => "some reference",:modelID => "modelID",:modelFileName => "",:fileUnits => "mm",:fileScaleFactor => "1",:materialID => "00e005a8-b29b-4196-ba4e-57ac1c4ce60c",:finishID => "bba2bebb-8895-4049-aeb0-ab651cee2597",:quantity => "1",:xDimMm => "81.266",:yDimMm => "159.935",:zDimMm => "10.096",:volumeCm3 => "15.5864",:surfaceCm2 => "260.288",:iMatAPIPrice => "25.0",:mySalesPrice => "26.0"}], :multipart => true})

In coffee script it works fine, when i try in the rest client it throws mentioned error.

mardi 11 juillet 2017

Reset counter after finishing iterating with the array elements

I’m doing this code but I can’t find the proper way to reset the counter after iterating with all the elements inside the array.

The idea is that after getting to the last song in the playlist you will get into the first one. Here is my code, i would really appreciate your help with this. Thanks in advance!

class Playlist
  attr_accessor :songs
  def initialize (name,songs)
    @name = name
    @songs = songs
  end

  def display_name
    @name
  end

  def number_of_songs
    "There are #{@songs.count} songs in the #{display_name}"
  end

  def add_song(song)
    @songs << song
    @songs
  end

  def next_song
    i = 0
    while i != 9
      p "Playing song: #{@songs[i]}"
      p "skip song? (Y/N)"
      user_input = gets.chomp
      if user_input.downcase == "y" && i != 8
        i += 1
      elsif user_input.downcase == "n" && i != 8
        puts "Playing song"
        sleep(1)
        print'.'
        sleep(1)
        print'.'
        sleep(1)
        sleep(1)
        print'.'
        sleep(1)
        print'.'
        sleep(1)
        sleep(1)
        print'.'
        sleep(1)
        print'.'
        sleep(1)
        print'.'
        puts
        puts
        i+=1
      end
    end
  end
end

playlist = Playlist.new("The Ultimate Playlist",["In My Life","Naive","She Moves In Her Own Way","Skinny Love","All My Life","All The Small Things","Real"])

p playlist.display_name
p playlist.number_of_songs
p playlist.add_song("California(Here We Come)")
puts
p playlist.next_song

uninitialized constant User::FavoriteRecipe

So I was trying to implement a favouriting system for an app of mine and followed this guide:

The particular setup you describe mixes several types of associations.

A) User and Recipe

First we have a User model and second a Recipe model. Each recipe belonging to one user, hence we have a User :has_many recipes, Recipe belongs_to :user association. This relationship is stored in the recipe's user_id field.

$ rails g model Recipe user_id:integer ...
$ rails g model User ...

class Recipe < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :recipes
end

B) FavoriteRecipe

Next we need to decide on how to implement the story that a user should be able to mark favorite recipes.

This can be done by using a join model - let's call it FavoriteRecipe - with the columns :user_id and :recipe_id. The association we're building here is a has_many :through association.

A User  
  - has_many :favorite_recipes  
  - has_many :favorites, through: :favorite_recipes, source: :recipe

A Recipe
  - has_many :favorite_recipes  
  - has_many :favorited_by, through: :favorite_recipes, source: :user 
      # returns the users that favorite a recipe

Adding this favorites has_many :through association to the models, we get our final results.

$ rails g model FavoriteRecipe recipe_id:integer user_id:integer

# Join model connecting user and favorites
class FavoriteRecipe < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :user
end

---

class User < ActiveRecord::Base
  has_many :recipes

  # Favorite recipes of user
  has_many :favorite_recipes # just the 'relationships'
  has_many :favorites, through: :favorite_recipes, source: :recipe # the actual recipes a user favorites
end

class Recipe < ActiveRecord::Base
  belongs_to :user

  # Favorited by users
  has_many :favorite_recipes # just the 'relationships'
  has_many :favorited_by, through: :favorite_recipes, source: :user # the actual users favoriting a recipe
end

C) Interacting with the associations

##
# Association "A"

# Find recipes the current_user created
current_user.recipes

# Create recipe for current_user
current_user.recipes.create!(...)

# Load user that created a recipe
@recipe = Recipe.find(1)
@recipe.user

##
#  Association "B"

# Find favorites for current_user
current_user.favorites

# Find which users favorite @recipe
@recipe = Recipe.find(1)
@recipe.favorited_by # Retrieves users that have favorited this recipe

# Add an existing recipe to current_user's favorites
@recipe = Recipe.find(1)
current_user.favorites << @recipe

# Remove a recipe from current_user's favorites
@recipe = Recipe.find(1)
current_user.favorites.delete(@recipe)  # (Validate)

D) Controller Actions

There may be several approaches on how to implement Controller actions and routing. I quite like the one by Ryan Bates shown in Railscast #364 on the ActiveRecord Reputation System. The part of a solution described below is structured along the lines of the voting up and down mechanism there.

In our Routes file we add a member route on recipes called favorite. It should respond to post requests. This will add a favorite_recipe_path(@recipe) url helper for our view.

# config/routes.rb
resources :recipes do
  put :favorite, on: :member
end

In our RecipesController we can now add the corresponding favorite action. In there we need to determine what the user wants to do, favoriting or unfavoriting. For this a request parameter called e.g. type can be introduced, that we'll have to pass into our link helper later too.

class RecipesController < ...

  # Add and remove favorite recipes
  # for current_user
  def favorite
    type = params[:type]
    if type == "favorite"
      current_user.favorites << @recipe
      redirect_to :back, notice: 'You favorited #{@recipe.name}'

    elsif type == "unfavorite"
      current_user.favorites.delete(@recipe)
      redirect_to :back, notice: 'Unfavorited #{@recipe.name}'

    else
      # Type missing, nothing happens
      redirect_to :back, notice: 'Nothing happened.'
    end
  end

end

In your view you can then add the respective links to favoriting and unfavoriting recipes.

<% if current_user %>
  <%= link_to "favorite",   favorite_recipe_path(@recipe, type: "favorite"), method: :put %>
  <%= link_to "unfavorite", favorite_recipe_path(@recipe, type: "unfavorite"), method: :put %>
<% end %>

That's it. If a user clicks on the "favorite" link next to a recipe, this recipe is added to the current_user's favorites.

I hope that helps, and please ask any questions you like.

The Rails guides on associations are pretty comprehensives and will help you a lot when getting started.

Posted by Thomas Klemm at Implement "Add to favorites" in Rails 3 & 4 but I keep getting an error: uninitialized constant User::FavoriteRecipe

some help would be appreciated

Delayed job picking attributes from table differently in different environments

I am using delayed job to queue a Model method in another Model like this:

article_loader.rb

date_value_in_string =  "2017-06-21 07:17:00"
Article.delay(:queue => 'article_load').article_loading([date_value_in_string])

Even though I have passed a String as an argument to the method, inside the method it gets converted to Time object in the production environment.

article.rb in production environment

def self.article_loading(args)
  date_value = args[0]
  p date_value.class # Time
end

While in development environment it is a string.

article.rb in development environment

def self.article_loading(args)
  date_value = args[0]
  p date_value.class # String
end

I don't know why this happens. Any help will be appreciated.

what is the best way to implement the generic action of controller where different response generated based on the params

Below code are written in the controller action where we are generating a different action based on the action parameter and secondary we are only generating the xml response on the basis of different action parameters.It's not necessary that every case of action consist result tag as parent.It's vary between action to action.

doc = EncodeDecode.decode(request.raw_post)
action =  parse_xml(doc/'action')  if (doc/'action').first

#    action = 'fetch_thread_colors'
case action
when 'create_customer_profile'
  result = Customer::CustomerCrud.create_customer_profile(doc)
  render :xml => "<result>#{result}</result>"

when 'create_customer_payment_profile' 
  result = Customer::CustomerCrud.create_customer_payment_profile(doc)
  render :xml => "<result>#{result}</result>"

How we can achieve the best way to implement because My problem is that it's to big in term of line of codes I am having more than 300-350 cases in the switch block.Is there any way something I can achieve it using metaprogramming But we also need to consider the point for memory efficient.

Solutions should be efficient ,clean and optimized to implement.

Any object oriented approach also can help me out.

lundi 10 juillet 2017

Namespaced models don't work with polymorphism and I need a workaround

Polymorphic relationships don't work when the models are namespaced in rails 3.1. Here is an example:

class Accounting::Request::Check < ActiveRecord::Base
  has_one :accounting_request, as: :requestable

  def self.table_name
    'accounting_request_checks'
  end
end

class Accounting::Request < ActiveRecord::Base
  belongs_to :requestable, polymorphic: true

  def self.table_name
    'accounting_requests'
  end
end


cr = Accounting::Request::Check.create!()
cr.create_accounting_request

Results in:

NameError: uninitialized constant Accounting::Request::Check::AccountingRequest

My question is, how can I work around this for the time being before we migrate to rails 5?

One solution I found was to add class_name: '::ClassName' but this doesn't work for me.

text_field_tag placeholder ignoring dynamic text after space in rails

I am using I18n for internationalization. for displaying place holder content in locale language in placeholder of text_field_tag im using following code.

<%= text_field_tag('email', "", class: 'form-control', placeholder: t('shared.enter_email')%>

And config/locales/en.yml content is as follows:

en:
  shared:
    enter_email: Enter Email

on running application, the content in the placeholder contains only Enter and its ignoring name because there is a space in-between.

i tried different syntax, all are producing same result. Is there a way to get this done?

samedi 8 juillet 2017

all nested descendants Deep nesting

I have Taxons table with all parent child records

<ActiveRecord::Relation [#<Spree::Taxon id: 1, parent_id: nil, position: 0, name: "Brands", permalink: "brands", taxonomy_id: 1, lft: 1, rgt: 20, icon_file_name: nil, icon_content_type: nil, icon_file_size: nil, icon_updated_at: nil, description: nil, created_at: "2017-06-14 08:52:19", updated_at: "2017-06-23 06:34:11", meta_title: nil, meta_description: nil, meta_keywords: nil, depth: 0>, #<Spree::Taxon id: 2, parent_id: nil, position: 0, name: "Brand", permalink: "brand", taxonomy_id: 2, lft: 21, rgt: 22, icon_file_name: nil, icon_content_type: nil, icon_file_size: nil, icon_updated_at: nil, description: nil, created_at: "2017-06-14 08:52:19", updated_at: "2017-06-14 08:52:22", meta_title: nil, meta_description: nil, meta_keywords: nil, depth: 0>, #<Spree::Taxon id: 3, parent_id: 1, position: 0, name: "Bags", permalink: "brands/bags", taxonomy_id: 1, lft: 2, rgt: 3, icon_file_name: nil, icon_content_type: nil, icon_file_size: nil, icon_updated_at: nil, description: nil, created_at: "2017-06-14 08:52:19", updated_at: "2017-06-21 05:03:52", meta_title: nil, meta_description: nil, meta_keywords: nil, depth: 0>, #<Spree::Taxon id: 4, parent_id: 1, position: 0, name: "Mugs", permalink: "brands/mugs", taxonomy_id: 1, lft: 4, rgt: 5, icon_file_name: nil, icon_content_type: nil, icon_file_size: nil, icon_updated_at: nil, description: nil, created_at: "2017-06-14 08:52:20", updated_at: "2017-06-14 08:58:29", meta_title: nil, meta_description: nil, meta_keywords: nil, depth: 0>, #<Spree::Taxon id: 5, parent_id: 1, position: 0, name: "Clothing", permalink: "brands/clothing", taxonomy_id: 1, lft: 6, rgt: 11, icon_file_name: nil, icon_content_type: nil, icon_file_size: nil, icon_updated_at: nil, description: nil, created_at: "2017-06-14 08:52:20", updated_at: "2017-06-23 06:34:11", meta_title: nil, meta_description: nil, meta_keywords: nil, depth: 0>, #<Spree::Taxon id: 6, parent_id: 5, position: 0, name: "Shirts", permalink: "brands/clothing/shirts", taxonomy_id: 1, lft: 7, rgt: 8, icon_file_name: nil, icon_content_type: nil, icon_file_size: nil, icon_updated_at: nil, description: nil, created_at: "2017-06-14 08:52:20", updated_at: "2017-06-20 06:10:16", meta_title: nil, meta_description: nil, meta_keywords: nil, depth: 0>, #<Spree::Taxon id: 7, parent_id: 5, position: 0, name: "T-Shirts", permalink: "brands/clothing/t-shirts", taxonomy_id: 1, lft: 9, rgt: 10, icon_file_name: nil, icon_content_type: nil, icon_file_size: nil, icon_updated_at: nil, description: nil, created_at: "2017-06-14 08:52:20", updated_at: "2017-06-23 06:34:11", meta_title: nil, meta_description: nil, meta_keywords: nil, depth: 0>, #<Spree::Taxon id: 8, parent_id: 1, position: 0, name: "Ruby", permalink: "brands/ruby", taxonomy_id: 2, lft: 12, rgt: 13, icon_file_name: nil, icon_content_type: nil, icon_file_size: nil, icon_updated_at: nil, description: nil, created_at: "2017-06-14 08:52:21", updated_at: "2017-06-20 06:09:31", meta_title: nil, meta_description: nil, meta_keywords: nil, depth: 0>, #<Spree::Taxon id: 9, parent_id: 1, position: 0, name: "Apache", permalink: "brands/apache", taxonomy_id: 2, lft: 14, rgt: 15, icon_file_name: nil, icon_content_type: nil, icon_file_size: nil, icon_updated_at: nil, description: nil, created_at: "2017-06-14 08:52:21", updated_at: "2017-06-23 06:34:11", meta_title: nil, meta_description: nil, meta_keywords: nil, depth: 0>, #<Spree::Taxon id: 10, parent_id: 1, position: 0, name: "Spree", permalink: "brands/spree", taxonomy_id: 2, lft: 16, rgt: 17, icon_file_name: nil, icon_content_type: nil, icon_file_size: nil, icon_updated_at: nil, description: nil, created_at: "2017-06-14 08:52:21", updated_at: "2017-06-14 08:58:29", meta_title: nil, meta_description: nil, meta_keywords: nil, depth: 0>, ...]>

I need a tree structure like this

parent1(first taxon(first record) with all child if it has)
  - child1
  - child2
  - child3
    - child7
    - child9
  - child4
  - child5
parent2(it has no child)
parent3(Not it has child)
  - child7
  - child9

i short i need each individual taxon with its nested child...

i have tried like

Taxon.all.each do |i| 
     i.self_and_descendants.each do |j|
       taxon_with_childs << j
     end

but this gives plain array but i want array with parent child nesting

i have also tried

Taxon.each_with_level(Taxon.root.self_and_descendants) do |taxon, level|
    taxon_with_childs << taxon
  end

but this is giving only first record's children and that to not deep nesting

Can any one please help me where i am wrong

vendredi 7 juillet 2017

ActiveAdmin looking up wrong table names for nested modules and ActiveRecord models

I have a module where all our Accounting ActiveRecord classes live within. I have an AR class called Requests and a subclass called Check (logically there will be multiple types of requests for accounting)

In my test suite for Accounting::Requests::Check I have the following tests:

subject(:check) { build(:check_with_items) } # Uses FactoryGirl

it "should have the right table name" do
   expect(Accounting::Requests::Check.table_name).to eq('accounting_request_checks')
end

it "should be a valid factory instance" do
  expect(check).to be_valid
end

Which pass and are correct.

However, when I do the following within an ActiveAdmin.register_page block:

ActiveAdmin.register_page 'Accounting Requests' do
  ... menu stuff

  controller do
    def index
      @check = Accounting::Requests::Check.new
    end

I get the this error:

PG::UndefinedTable: ERROR:  relation "accounting_checks" does not exist

My test ensures that this model has the right table name, being "accounting_request_checks", yet AA is looking for "accounting_checks".

Directory structure:

/models
   /accounting
     request.rb
     /requests
       check.rb  

Here are the class declarations:

class Accounting::Requests < ActiveRecord::Base

class Accounting::Requests::Check < ActiveRecord::Base

Why is active admin looking up the incorrect table name?

I've also tried changing requests from a class to a module with a function using self.table_name_prefix (that's a Rails 3.1 method)


update:

It's not ActiveAdmin - in rails console doing Accounting::Requests::Check.new gives the same error.

expected ArgumentError but nothing was raised

My spec is:

expect { result }.to raise_error(ArgumentError)
#=> expected ArgumentError but nothing was raised

When I put debugger in the code, result is:

(pry) output error: #<ArgumentError: (...)

What's wrong with the spec? I use rspec-given

jeudi 6 juillet 2017

How to fix Country-State-Select gem undefined method issue?

In a implementation of gem: http://ift.tt/2tXriyB

When i go to Post Job new page show this error on the log

undefined method `country' for #

I've tried to put the

accepts_nested_attributes_for

in the job model, but did not worked.

Someone have any hint to spare?

Job Model

 class Job < ActiveRecord::Base

    belongs_to :user
    belongs_to :location
    accepts_nested_attributes_for :location, allow_destroy: true
    default_scope -> { order(created_at: :desc) }

    end

Location Model

 class Location < ActiveRecord::Base

    has_many :users
    has_many :jobs

    end

Job new view

 <%= simple_form_for @job do |f| %>
    <%= f.simple_fields_for :location do |l| %>
     <%= l.input :country, label: "Country", collection: CountryStateSelect.countries_collection %>
    <%= l.input :state, CountryStateSelect.state_options(label: "State / Province", form: f, field_names: { :country => :country, :state => :state } ) %>
    <%= l.input :city, CountryStateSelect.city_options(label: "City ", form: f, field_names: {  :state => :state, :city => :city } ) %>

          <% end %>
    <%= f.input :name, label: 'Name', error: 'Name is mandatory' %>
       <%= f.input :description, placeholder: 'user@domain.com' %>

    <%= f.button :submit %>
    <% end %>

String value gets converted to Time object when a model method is called using delayed job

I am using delayed job to queue a Model method in another Model like this:

article_loader.rb

date_value_in_string =  "2017-06-21 07:17:00"
Article.delay(:queue => 'article_load').article_loading([date_value_in_string])

Even though I have passed a String as an argument to the method, inside the method it gets converted to Time object.

article.rb

def self.article_loading(args)
  date_value = args[0]
  p date_value.class # Time
end

I don't know why this happens. Any help will be appreciated.

mercredi 5 juillet 2017

Mysql server cannot connect through mysql socket (2) when app is running in vagrant Ubuntu VM

I have a rails app which was perfectly working for me in my default rails development environment, but when I installed Vagrant VM and ran my app on Ubuntu 12.04 I have this error that says

Mysql2::Error (Can't connect to local MySQL server through socket 'MySQL' (2)):

As far as I understood is that my ubuntu VM cannot load Mysql server through socket MYSQL that was working for my default windows, so I tried to remove socket: MySQL line from my rails database.yml

default: &default


adapter: mysql2
  encoding: utf8
  pool: 5
  username: root
  password: xxxxx
  socket: MySQL
  host: localhost

But then I get the error saying my database is not found, I can't seem to fig out how can I look for my database from window and load it in Ubuntu VM ??

here is the log that gives absolutely no info .. :/

Mysql2::Error (Can't connect to local MySQL server through socket 'MySQL' (2)):

/home.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/mysql2-0.4.5/lib/mysql2/client.rb:89:in `connect'
/home.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/mysql2-0.4.5/lib/mysql2/client.rb:89:in `initialize'
/home.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activerecord-5.0.1/lib/active_record/connection_adapters/mysql2_adapter.rb:25:in `new'
/home.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/ ...so on

Any Ideas on how to make it work ?

mardi 4 juillet 2017

Get parent objects without active childs

I've two models, Doctor and Clinic where a doctor has_many clinics.

Clinic have doctor_id and a boolean active field.

What I want:

I want to get all doctors which does not have any active (active field is true) clinics i.e. either doctor does not have any clinics or does not have any clinics where active field is true.

What I've tried so far:

Try 1:

scope :incomplete_doctors, -> { includes(:clinics)
                                .where("( doctor_clinics.id IS NULL ) OR
                                        ( doctor_clinics.id IS NOT NULL AND
                                            doctor_clinics.active=?)", false )
                              }

Try 2:

scope :incomplete_doctors, -> { where("id NOT IN (?)", self.includes(:clinics)
                            .where("( doctor_clinics.doctor_id IS NULL ) OR
                                      ( doctor_clinics.doctor_id IS NOT NULL AND
                                          doctor_clinics.active=?)", false )
                            .select(:id))
                            }

Try 3:

SELECT "doctors".* FROM "doctors"
  LEFT OUTER JOIN "doctor_clinics" ON "doctor_clinics"."doctor_id" = "doctors"."id"
  WHERE ( ( doctor_clinics.id IS NULL ) OR
          ( doctor_clinics.id IS NOT NULL AND
              doctor_clinics.active='f'))
  GROUP BY doctors.id
    HAVING 'true' <> ANY(array_agg(DISTINCT doctor_clinics.active::TEXT));

Success:

I'm able to achieve desired output using following method, but I want to achieve this using a SQL query.

def active_clinics
  clinics.active_clinics # active_clinics is a scope in Clinic model while give all active clinics
end

def self.incomplete_doctors
  (Doctor.all.map { |d| d unless d.active_clinics.present? }).compact
end

Recaptcha::RecaptchaError in Articles#show No site key specified

Help please. I get:

"Recaptcha::RecaptchaError in Articles#show No site key specified."

And I do not understand where my mistake is. :( Please tell me how to protect comments?

http://ift.tt/2tmJ9eW

Gem::Ext::BuildError: ERROR: Failed to build gem native extension for rails version 4.2.6

i have created new rails app and try to run bundle install it shows this error,

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
current directory: /var/lib/gems/2.3.0/gems/json-1.8.6/ext/json/ext/generator/usr/bin/ruby2.3 -r ./siteconf20170704-11395-12tpg5u.rb extconf.rb
mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h
extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.3.0/gems/json-1.8.6 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/json-1.8.6/gem_make.out

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

Kindly send me some suggestions,Thanks in Advance.

lundi 3 juillet 2017

Model serilize hash turned from hash to string when saving object

ruby 2.3.3, rails 3.2.22.5

Hi. I'm using a serialized :logs, Hash in a User model, when saving the logs hash- afterwards it's being retrieved as string instead of Hash.

How it happen:

  1. assign value to logs hash
  2. save user object
  3. now logs hash is a string..

So for user when assigning value to logs hash: user.logs[2] = 4, then saving

class User < ActiveRecord::Base
  serialize :logs, Hash # in database it's a text type
end

An example in the rails console:

# rails console
test_user_id = 3
user = User.find(test_user_id)
user.logs = {}
user.save

user.logs # => {} # great
User.find(test_user_id).logs # => {} # great
# now trying to add value and save:

# 1. assign value to logs hash
user.logs[Time.now] = {:field_id=>6} # => {:field_id=>6}
# 2. save user object:
user.save
# 3. now logs hash is a string..
user.logs
#=> "---\n2017-07-03 19:33:34.938364000 +03:00:\n  :field_id: 6\n" 
# why it turned to string ?!?!

User.find(test_user_id).logs # same here:
# => "---\n2017-07-03 19:33:34.938364000 +03:00:\n  :field_id: 6\n"

Any ideas?

dimanche 2 juillet 2017

Ruby on rails devise form helper

I'm starting with ruby and rails and I want to create a helper to show this form :

<%= form_for( :user, :url => session_path( :user) ) do |f| %>
<%= f.text_field :email %>
<%= f.password_field :password %>
<%= f.check_box :remember_me %>
<%= f.label :remember_me %>
<%= f.submit 'Sign in' %>
<%= link_to "Forgot your password?", new_password_path( :user) %>
<% end %>

So I just have to call my function show_login-form and display my form :) but I don't know how :(

Thanks