dimanche 3 janvier 2016

How to implement select2 gem with contents retrieved from a table in Rails (association)

I am trying to implement select2 rails gem in my project. But it is not rendering properly.

My question is, I have a table called college which consists of a list of colleges. I want to implement drop down with search using select2 gem. I need to how to call the select2 from the form. When I use collection_select, I am getting two dropdowns, one of collection_select and other from select2.

Can anyone tell me how to do this?

samedi 2 janvier 2016

Rails grouped_collection_select child issue

I have a model Member that has a new creation form. The form allows users to assign a department and position for each member to be a part of. The positions are relative to the department. In a separate part of the app, users can create departments and create/assign positions. I am trying to create a grouped_collection_select for the new members page, however my positions are not showing up, just departments as categories. I believe this is an association issue, where the positions are not being associated with their respective dept. I have the string department_id in my positions model, however I don't think the selection is able to read that as the parent. If anyone can point me in the correct direction that'd be awesome.

The line giving an error: (from the new members form_for)

<%= f.grouped_collection_select :title, Department.where(production_id: current_user.default_working_production_id).order(:department), :positions, :department, :id, :position, include_blank: true %>

My schema looks like:

create_table "departments", force: true do |t|
    t.string   "department"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "production_id"
end

create_table "positions", force: true do |t|
    t.string   "position"
    t.string   "department_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "production_id"
end

My model associations:

class Member < ActiveRecord::Base
    belongs_to :company
    validates :firstname, presence: true
    validates :email, presence: true
    def name
        "#{firstname} #{lastname}"
    end
end

class Department < ActiveRecord::Base
    has_many :positions
    attr_accessible :department
    validates :department, presence: true
end

class Position < ActiveRecord::Base
    belongs_to :department
    attr_accessible :department_id, :position, :department
end

does not change the options

I'm trying to make the options to search by company name or identification of the company with the options on rails. I'm using it with simple_form, someone can help me to choose the options.

the line number is 60 which says : <%= f.collection_radio_buttons :options, [['C', 'CLIENTE'] ,['R', 'RUC']], :first, :last %>

<%= simple_form_for(@referral_guide) do |f| %>
  <%= f.error_notification %>

    <div class="form-inputs">
    <table>
    <tr>
        <th class="text-center" width="450px"><%=h f.input :fecha, label: 'Fecha de Emisión' %></th>
        <th class="text-center" width="450px"><%=h f.input :fecha_vencimiento, label: 'Fecha de Vencimiento' %></th>
    </tr>
    </table>

    <table>
    <tr>
        <th class="text-center" width="900px"><strong>La Guia de Remisión incluye Impuesto (Se genera en caso la Factura) ? : </strong><%= f.collection_radio_buttons :impuesto, [['S', 'Si'],  ['N', 'No']], :first, :last %></th>
    </tr>
    </table>

    <table>
    <tr>
        <th class="text-center" width="150px"><%=h f.input :moneda, collection: ["S/.", "US$"], label: 'Tipo de Moneda', :input_html => { :style => 'width: 80'} %></th>
        <th class="text-center" width="200px"><%=h f.input :costo, label: 'Costo mínimo', :input_html => { :style => 'width: 190' } %></th>
        <th class="text-center" width="200px"><%=h f.association :status, :input_html => { :style => 'width: 180'} %></th>
        <th class="text-center" width="320px"><%=h f.input :orden_compra, label: 'Orden de Compra', :input_html => { :style => 'width: 240' } %></th>
    </tr>
    </table>

    <table>
    <tr>
        <th class="text-center" width="450px"><%=h f.association :sale, label: 'Vendedor', :input_html => { :style => 'width: 420px'},label_method: "#{:nombre}", value_method: :id %></th>
        <th class="text-center" width="450px"><%= f.association :motivo, label: 'Motivo de Traslado', label_method: "#{:nombre}", value_method: :id, :input_html => {:style => 'width: 420px'} %> </th>

    </tr>
    </table>

    <table>
    <tr>
        <th class="text-center" width="225px"><%=h f.input :marca_placa, label: 'Marca y Número de Placa', :input_html => { :style => 'width: 200px' }%></th>
        <th class="text-center" width="225px"><%=h f.input :numero_constancia, label: 'Número de Constancia de Inscripción', :input_html => { :style => 'width: 200px' } %></th>   
        <th class="text-center" width="225px"><%=h f.input :numero_licencia, label: 'Número de Licencia', :input_html => { :style => 'width: 200px' } %></th>
        <th class="text-center" width="225px"><%=h f.input :chofer, label: 'chofer', :input_html => { :style => 'width: 200px' } %></th>
    </tr>
    </table>

    <table>
    <tr>
        <th class="text-center" width="300px"><%=h f.input :nombre_transporte, label: 'Nombre de la empresa de Transportes', :input_html => { :style => 'width: 250px' } %>
        <th class="text-center" width="300px"><%=h f.input :ruc_transporte, label: 'Ruc de la empresa de Transportes', :input_html => { :style => 'width: 250px' } %>
        <th class="text-center" width="300px"><%=h f.input :chofer_transporte, label: 'Chofer de la empresa de Transportes', :input_html => { :style => 'width: 250px' } %></th>
    </tr>
    </table>

    <table>
    <tr>
    <th class="text-center" width="600px"><%=h f.association :customer, label_method: "#{:nombre}", value_method: :id, prompt: "Debes buscar el nombre de la empresa", label: 'Empresa', :input_html => { :style => 'width: 550px' } %></th>
    <th class="text-center" width="300px"><%=h f.association :customer, label_method: "#{:ruc}", value_method: :id, prompt: "Debes buscar el ruc de la empresa", label: 'RUC', :input_html => { :style => 'width: 250px' } %></th>    
    </tr>
    </table>

    <p><strong>Debe Seleccionar las opciones para buscar el nombre o ruc del cliente</strong></p>
    <%= f.collection_radio_buttons :options, [['C', 'CLIENTE'] ,['R', 'RUC']], :first, :last %>
    <% if f.object.options == 'C' %>
    <%=h f.association :customer, label_method: "#{:nombre}", value_method: :id, prompt: "Debes buscar el nombre de la empresa", label: 'Empresa', :input_html => { :style => 'width: 550px' }  %>
    <% else %>
    <%=h f.association :customer, label_method: "#{:ruc}", value_method: :id, prompt: "Debes buscar el ruc de la empresa", label: 'RUC', :input_html => { :style => 'width: 250px' } %>
    <% end %>

    <%=h f.input :numero_factura, label: 'Ingresar el Numero de Factura que vas a generar, si no desea generar, poner cero', :input_html => { :style => 'width: 250px' } %>

    <div>

    <table id="items">
          <tr>
            <th class="text-center" width="60px">ITEM</th>
            <th class="text-center" width="225px">DESCRIPCION</th>
            <th class="text-center" width="100px">CANTIDAD</th>
            <th class="text-center" width="110px">PRECIO</th> 
            <th class="text-center" width="150px">TOTAL</th>
            <th class="text-center" width="63px"></th>
          </tr>
    </table>
    <% @totales = 0.00 %>   
<%= simple_nested_form_for @referral_guide, :wrapper => false do |g| %>
    <table id="detail_referral_guides">
    <%= g.simple_fields_for :detail_referral_guides do |p| %>
    <tr class="fields">
        <th align="center" width="74px" class="text-center"><%= p.input :item, label: false %></th>
        <th align="center" width="276px" class="description"><%= p.input :description, label: false, input_html: {:rows => 3} %></th>
        <th align="center" width="123px" class="text-center"><%= p.input :cantidad, label: false %></th>
        <th align="center" width="135px" class="text-right"><%= p.input :precio, label: false %></th>
    <% @total_price = p.object.cantidad.to_s.to_d * p.object.precio.to_s.to_d %>
        <th align="right" width="184px" class="text-right"><%= number_with_precision(@total_price, :delimiter => ',', :separator => '.' ) %></th>
        <th align="center" width="77px" class="text-center"><%= p.link_to_remove "", class: "btn btn-danger fa fa-trash" %></th>
    <% @totales = @totales + @total_price %>
    </tr>
    <% end %>
    </table>

      <% if f.object.impuesto == 'S' %>
        <% @valor_venta = @totales / (1 + ( @empresa.impuesto / 100.00)) %>
        <% @valor_igv = @valor_venta * (@empresa.impuesto / 100.00) %>
        <% @valor_totales = @totales %>
      <% else %>
        <% @valor_venta = @totales %>
        <% @valor_igv = @totales * (@empresa.impuesto / 100.00) %>
        <% @valor_totales = @valor_venta + @valor_igv %>
      <% end %>
    <table id="items">
        <tr>
            <th width="700px"></th>
            <th class="text-center" width="110px">VALOR DE VENTA : </th> 
            <th class="text-right" width="150px"><%= number_with_precision(@valor_venta, :delimiter => ',', :separator => '.') %></th>  
        </tr>

        <tr>
            <th width="700px"></th>
            <th class="text-center" width="110px">I.G.V. : </th>            
            <th class="text-right" width="150px"><%= number_with_precision(@valor_igv, :delimiter => ',', :separator => '.') %></th>
        </tr>

        <tr>
            <th width="700px"></th>
            <th class="text-center" width="110px">TOTAL : </th> 
            <th class="text-right" width="150px"><div class="due"></div><%= number_with_precision(@valor_totales, :delimiter => ',', :separator => '.') %></th>
        </tr>
    </table>

    <% if f.object.impuesto == 'S' %>
        <p><strong>LOS PRECIOS OFERTADOS ESTAN INCLUIDOS I.G.V.</strong></p>
    <% else %>
        <p><strong>LOS PRECIOS OFERTADOS NO ESTAN INCLUIDOS I.G.V.</strong></p>
    <% end %>

    <br>
    <br>
    <p><%= g.link_to_add "Adicionar Producto", :detail_referral_guides, :data => { :target => "#detail_referral_guides" }, class: "btn btn-primary" %></p>
  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>
<% end %>

vendredi 1 janvier 2016

Use MySQL from AMPPS with Rails

I'm trying to use Rails with the MySQL bin from Ampps, but when I run the command rails generate scaffold User name:string email:string I get the following error:

dyld: lazy symbol binding failed: Symbol not found: _mysql_server_init
Referenced from: /Users/myusername/.rvm/gems/ruby-2.2.1/gems/mysql2-0.4.2/lib/mysql2/mysql2.bundle
  Expected in: flat namespace

dyld: Symbol not found: _mysql_server_init
  Referenced from: /Users/myusername/.rvm/gems/ruby-2.2.1/gems/mysql2-0.4.2/lib/mysql2/mysql2.bundle
  Expected in: flat namespace

I have already configured Ampps Mysql with my environment but I can not managed to make it work with rails, I have the following configurations.

$ which mysql                                          
/Applications/AMPPS/mysql/bin/mysql

$ echo $PATH
/Users/myusername/.rvm/gems/ruby-2.2.1/bin:/Users/myusername/.rvm/gems/ruby-2.2.1@global/bin:/Users/myusername/.rvm/rubies/ruby-2.2.1/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/myusername/.rvm/gems/ruby-2.2.1/bin:/Users/myusername/.rvm/gems/ruby-2.2.1@global/bin:/Users/myusername/.rvm/rubies/ruby-2.2.1/bin:/Applications/AMPPS/php-5.4/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/myusername/.rvm/bin:/Users/myusername/.rvm/bin:/Applications/AMPPS/mysql/bin

$ ls -l /usr/local/lib/libmy*.dylib 
lrwxr-xr-x  1 myusername  admin  53 Jan  1 19:30 /usr/local/lib/libmysqlclient.18.dylib -> /Applications/AMPPS/mysql/lib/libmysqlclient.18.dylib

I have tried doing commands but with no success:

$ gem install mysql2 -- --with-mysql-lib=/Applications/AMPPS/mysql/lib --with-mysql-include=/Applications/AMPPS/mysql/include --with-mysql-config=/Applications/AMPPS/mysql/bin/mysql_config

And

bundle config build.mysql2 --with-mysql-lib=/Applications/AMPPS/mysql/lib --with-mysql-include=/Applications/AMPPS/mysql/include --with-mysql-config=/Applications/AMPPS/mysql/bin/mysql_config
bundle install

Any ideas?

Rails - generate a Scaffold within a Namespace

I have an early stage project that I am trying to namespace before organization becomes a problem, following the most clear and up to date post I can find regarding namespacing.

But it doesn't work as magically as I'd hoped. How do I generate a Scaffold within a Namespace that is functional? I believe this is an issue of plurality vs. singularity.

Example:

words
  languages
  definitions

users

Generate:

rails g scaffold Words/Language name:string
rails g scaffold Words/Definition name:string
rails g scaffold Word name:string language:references definition:references user:references

After the above, there is an exception for word.language but not word.user:

irb(main)> word = Word.find(1)
  Word Load (0.3ms)  SELECT  "words".* FROM "words" WHERE "words"."id" = ? LIMIT 1  [["id", 1]]
=> #<Word id: 1, name: "Hello", language_id: 1, definition_id: 1, user_id: 1>

irb(main)> word.user
  User Load (0.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
=> #<User id: 1, name: "admin">

irb(main)> word.language
NameError: uninitialized constant Word::Language

Rails generates two models, both word.rb and words.rb:

app/models/word.rb

class Word < ActiveRecord::Base
  belongs_to :language
  belongs_to :definition
  belongs_to :user
end

app/models/words.rb

module Words
  def self.table_name_prefix
    'words_'
  end
end

How do I combat this issue of singular vs. plural with namespaced generated scaffolds?

ruby on rails - routes error porting from 3.x to 4.x

i've started porting one of my apps from rails 3.x to rails 4.x....

when i start the app in development, i receive a route definition related error:

=> Booting WEBrick
=> Rails 4.2.5 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
Exiting
/home/francesco/.rvm/gems/ruby-2.2.2@Best-i-gest_v2/gems/actionpack-4.2.5/lib/action_dispatch/routing/route_set.rb:549:in `add_route': Invalid route name, already in use: 'app_settings'  (ArgumentError)
You may have defined two routes with the same name using the `:as` option, or you may be overriding a route already defined by a resource with the same naming. For the latter, you can restrict the routes created with `resources` as explained here: 
http://ift.tt/1g4FQcF
.....

here part of my routes.rb file containing the routes marked as double defined:

.....
get 'app_settings' => 'admin/app_settings#index', :as => 'app_settings'
put 'app_settings' => 'admin/app_settings#index', :as => 'app_settings'
post 'app_settings' => 'admin/app_settings#index', :as => 'app_settings'
post 'app_settings/upload' => 'admin/app_settings#upload_logo', :as => 'app_settings/upload'
.....

i've defined these routes because i'm going to manage all actions related to application setting using the 'index' action only (the app has a single db record storing all settings, this record is automatically created at the first time the user will load page, then updated when it saves) as you can see here:

# only one record here! it will store all the application settings
def index
  # manages all the controller actions inside the index...
  if request.get?
    # this is a get request... returns the first settings record or a new one if none exists!
    @app_settings = !AppSettings.all.first.nil? ? AppSettings.all.first : AppSettings.new
  elsif request.post?
    # this is a post request, the settings record will be created
    @app_settings = AppSettings.new(params[:app_settings])
    @app_settings.save
  elsif request.put?
    # this will update the existing app_settings record
    @app_settings = AppSettings.find_by_id(params[:app_settings][:id].to_i)
    @app_settings.update_attributes(params[:app_settings])
  end

  # renders the index page
  render "index"
end

i'm looking for a way to correct the routes.rb file (keeping my controller and view as is!!) or an alternative way to manage this issue!!

waiting your suggestions, many thanks in advance for your time,

francesco

Validations conflicts in Rails

I am working on a project and I am facing a problem which I tried to solve but no progress.

All these happened when I started to implement "Forgot Password" functionality for resetting password. I have a User Model which has validations for password and password_confirmation. I used these for registration and are working fine.

But for this functionality I am using a new controller called "PasswordResets". I am generating a string called "password_reset_token" for my users table. And there is "password_reset_sent_at" which records the time a user asks for a reset. The process goes like this;

1) The User clicks Forgot Password?

2) He is redirected to a page where he is asked to enter his email.

3) Controller checks if the email is present in database, if yes then ;

    3.1) I generate a random password token by using SecureRandom and also time when he started the request. 
    3.2) Now the save happens here for sending the mail to user. Here the problem occurs. The password_reset_token is not getting saved into table.

The reason behind that is I am using validations for password and password _confirmation in user.rb. Here the action taking place is ":update", so on update the record is asking for password and password_confirmation to be sent along with password_reset_token and the time.

But I tried solving by keeping validations as :on => :create, now it is working well but when I use the link for resetting my validations will not work for password and password_confirmation. This is like a deadlock for me. I know this is bit confusing, I am pasting some code to understand the problem.

My PasswordResets Controller create action

    def create
    user= User.find_by_email(params[:email])
    if user
      user.send_password_reset
      UserMailer.password_reset(self).deliver
      flash[:success] = "Email sent with password reset instructions."
      redirect_to root_url
    else
      flash[:error] = "Email doesn't exit."
      render 'password_resets/new'
    end
  end

My User Model (user.rb)

 class User < ActiveRecord::Base

  has_secure_password

  EMAIL_REGEX = /\A[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}\Z/i


  validates_confirmation_of :password_confirmation

  validates :username, :presence => true,
                       :uniqueness => true,
                       :length => {:within => 8..25}
  validates :email, :presence => true,
                    :uniqueness => true,
                    :format => EMAIL_REGEX

  validates :password, :length => {:within => 8..25}

  validates :password_confirmation, :presence => true

  def send_password_reset
    generate_token(:password_reset_token)
    self.password_reset_sent_at = Time.zone.now
    save!
    UserMailer.password_reset(self).deliver
  end


  def generate_token(column)
    begin
      self[column] = SecureRandom.urlsafe_base64
    end while User.exists?(column => self[column])
  end


end

The problem can be solved by using :on=>:create for validations as :update request is taking place. But when I get confirmation link in my console and use it, the validations for password and password_confirmation dont work as the action here is :update. This is like a deadlock.

I am really grateful to anyone who help me out from this maze.

Thank you.