mardi 31 octobre 2017

Rails nested models and child validation

I have two models.

Exemplary:

class Book < ActiveRecord::Base
  has_many :pages, dependent: :destroy
  accepts_nested_attributes_for :pages, allow_destroy: true
end

class Page < ActiveRecord::Base
  belongs_to :book

  validate_on_create :count_within_bounds

  LIMIT = 200

  private

  def count_within_bounds
    if self.book.pages.count >= LIMIT
      errors.add_to_base("Number of pages cannot be greater than #{LIMIT}")
    end
  end
end

Now when update the book through a nested form everything is working just fine. I can edit let's say the title and add new pages. But if the page validation fails the other changes made to the book model are not getting saved either.

I understand that it's all being saved in one transaction but is there a way to persist the parent regardless without having to do it manually in two steps, i.e. saving the parent first without pages_attributes?

Query - Ruby on Rails

Please, how do I make this query in Rails?

SELECT *, count(v.id) numero_votos FROM ideas i left join votes v on v.idea_id = i.id group by i.id order by numero_votos desc, i.created_at

I tried this...

@listOfIdeas = Idea.find(:all, joins: "LEFT JOIN 'votes' on votes.idea_id = ideas.id",
                                    select: "ideas.*, count(votes.id) numero_de_votos",
                                    group: "ideas.id",
                                    order: "numero_de_votos DESC, ideas.created_at DESC")

But, didn't work, it's showing me this message:

Couldn't find all Ideas with 'id': (all, {:joins=>"LEFT JOIN 'votes' on votes.idea_id = ideas.id", :select=>"ideas.*, count(votes.id) numero_de_votos", :group=>"ideas.id", :order=>"numero_de_votos DESC, ideas.created_at DESC"}) (found 0 results, but was looking for 2)

Rails version: 5.1.4

Thanks!

Create data through a form edit from another controller via nested attributes

I'm trying through an edit form to add values ​​to actions in other controllers. I have the following models:

class Day < ApplicationRecord
  belongs_to :goal
  has_many :day_salesmen, dependent: :destroy
  has_many :salesmen, through: :day_salesmen
  validates_presence_of :date_day, :goal_id

  accepts_nested_attributes_for :day_salesmen
end

class Salesman < ApplicationRecord
  belongs_to :company
  has_many :goal_salesmen, dependent: :destroy
  has_many :goals, through: :goal_salesmen

  has_many :day_salesmen, dependent: :destroy
  has_many :days, through: :day_salesmen

end

class DaySalesman < ApplicationRecord
  belongs_to :day
  belongs_to :salesman

  accepts_nested_attributes_for :salesman
end

In other words, I have a day that can have many employees and many employees can be part of a day.

When I edit the day I want it to be possible to add employee and associate them to my day through the day_salesman table.

I'm trying to do this, but I get the following error log:

ActionController::ParameterMissing (param is missing or the value is empty: salesman):

app/controllers/salesmen_controller.rb:49:in `params_salesman'
app/controllers/salesmen_controller.rb:17:in `create'
  Rendering /box/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
  Rendering /box/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
  Rendered /box/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (32.8ms)
  Rendering /box/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
  Rendered /box/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (28.5ms)
  Rendering /box/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
  Rendered /box/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (53.3ms)
  Rendered /box/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (216.0ms)
Started POST "/companies/3/salesmen" for 172.24.0.1 at 2017-10-31 15:21:09 +0000
Cannot render console from 172.24.0.1! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by SalesmenController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"/5ULp1WOehoaJIZL0SaCSDYU9MssS7ZQ5EfyTkmZCyFSvogj6lOtxOTuNTx8AjdeRjAnkkd3XhD5V30/QAXijg==", "day"=>{"value"=>"400", "salesman"=>{"name"=>"Mauro"}}, "commit"=>"Create", "company_id"=>"3"}
  [1m[36mOwner Load (3.5ms)[0m  [1m[34mSELECT  "owners".* FROM "owners" WHERE "owners"."id" = $1 ORDER BY "owners"."id" ASC LIMIT $2[0m  [["id", 1], ["LIMIT", 1]]
Completed 400 Bad Request in 108ms (ActiveRecord: 12.7ms)

My controllers are:

class SalesmenController < ApplicationController
  before_action :find_salesman, only: [:edit, :update, :destroy, :show]

  def index
    @salesman = current_owner.companies.find(params[:company_id]).salesman
  end

  def new

  end

  def show

  end

  def create
    @salesman = Salesman.new(params_salesman)
    if @salesman.save
      flash[:notice] = "Salesman saved!"
    else
      flash.now[:error] = "Cannot create salesman!"
      render :new
    end
  end

  def edit
  end

  def update
    if @salesman.update(params_salesman)
      flash[:notice] = "salesman updated!"
    else
      flash.now[:error] = "Could not update salesman!"
      render :edit
    end
  end

  def destroy
    @salesman.destroy
  end

  private

  def find_salesman
    @salesman = Salesman.find(params[:id])
  end

  def params_salesman
    params.require(:salesman).permit(:name).merge(company_id: params[:company_id])
  end
end

DaysController:

class DaysController < ApplicationController
  before_action :find_day, only: [:show, :edit, :update]

  def index
    @day = current_owner.companies.find(params[:company_id]).goal.find(params[:goal_id]).days
  end

  def show
  end

  def edit
    @dayup = Day.new
    @day_salesmen = @dayup.day_salesmen.build
    @salesman = @day_salesmen.build_salesman
  end

  def update
    if @day.update(params_day)
      flash[:notice] = "Day updated!"
      redirect_to company_salesman_path(:id => @day.id)
    else
      flash.now[:error] = "Could not update day!"
      render :edit
    end
  end

  private

  def find_day
    @day = Day.find(params[:id])
  end

  def params_day
    params.require(:day).permit(:value, day_salesman_attributes: [:id, salesman_attributes:[:name]]).merge(goal_id: params[:goal_id])
  end
end

My view edit for controller days:

<%= form_for(@dayup, url: company_salesmen_path) do |f| %>
  <%= f.label :value_of_day %>
  <%= f.number_field :value %>
  <%= f.fields_for :day_salesman do |ff| %>
    <%= f.fields_for :salesman do |fff| %>
      <%= fff.label :names_of_salesmen %>
      <%= fff.text_field :name %>
    <% end %>
  <% end %>
  <%= f.submit "Create" %>
<% end %>

My routes are:

Rails.application.routes.draw do
  root to: 'companies#index'
  resources :companies do
    resources :salesmen
    resources :goals do
      resources :days
    end
  end
  devise_for :owners, :controllers => { registrations: 'registrations' }
  # For details on the DSL available within this file, see http://ift.tt/GVpneB
end

I'm trying to use nested attributes, but it seems like I'm applying the wrong way, can someone help you get a salesman through the edit form of the days and relate them?

ruby remove empty, nil elements from array of array and have and have array of string

I have this array of arrays:

["[]", "[\"http://ift.tt/2gZwhtF\"]", "[\"http://ift.tt/2yZJbid\"]", "[]", "[]", "[]", "---\n- http://ift.tt/2gZwi0H\n", "--- []\n", "---\n- http://ift.tt/2yZJbPf\n", "--- []\n", "--- []\n", "---\n- https://somewebsite.com\n", "---\n- http://ift.tt/2gZ6rWF\n", nil, nil, nil, nil, nil]

How can i :
1- remove all the empty, nil element
2- have an array of string:

["http://ift.tt/2gZwhtF", "http://ift.tt/2yZJbid", "http://ift.tt/2gZwi0H", "http://ift.tt/2yZJbPf, "https://somewebsite.com", "http://ift.tt/2gZ6rWF"]

SAML Authentication with Okta Identity Provider

I have setup everything for saml authentication with Okta. By default it gives NameID as application username but i want to use employeeNumber.

So i have also done with the mapping between okta user profile -> app user profile. Like -

user.employeeNumber(okta user profile) -> userName(app user Name)

But still i am getting app username in SAML assertion but not the employeeNumber.

Can anyone tell me how can this can be achieved or if i am missing something?

lundi 30 octobre 2017

Hi guys, i want to use work flow on rails,

So i am using git hub references, but i cant install gem 'rails work flow', Error: while using command rake db migrate.This file is used to install my app http://ift.tt/2lrsDKB if any one already used that gem or this logic please give a guidance.

dimanche 29 octobre 2017

How to generate Modulus and Exponent for sgining XML doc ?

I Want sign XML doc. I am doing following for generating signature(ruby).

unsigned_xml = <<-xml
  <note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
 </note>
 xml

sdoc = Xmldsig::SignedDocument.new(unsigned_xml)
signature_xml = File.read('signature.xml')
sdoc.document.children.children.last.add_next_sibling(signature_xml)
privkey = OpenSSL::PKey::RSA.new(File.read('bd-key.pem'))
sdoc.sign(privkey)

Please see signature.xml and output below,

signature.xml

<Signature xmlns="http://ift.tt/uq6naF">
  <SignedInfo>
    <CanonicalizationMethod Algorithm="http://ift.tt/y9fQ1c"/>
    <SignatureMethod Algorithm="http://ift.tt/zf1Wx4"/>
    <Reference URI="">
      <Transforms>
        <Transform Algorithm="http://ift.tt/A1C4L2"/>
      </Transforms>
      <DigestMethod Algorithm="http://ift.tt/1jbsD3O"/>
      <DigestValue/>
    </Reference>
  </SignedInfo>
  <SignatureValue/>
  <KeyInfo>
    <KeyValue>
      <RSAKeyValue>
        <Modulus></Modulus>
        <Exponent></Exponent>
      </RSAKeyValue>
    </KeyValue>
  </KeyInfo>
</Signature>

output.xml

<?xml version="1.0"?>
<note>
      <to>Tove</to>
      <from>Jani</from>
      <heading>Reminder</heading>
      <body>Don't forget me this weekend!</body>
   <Signature xmlns="http://ift.tt/uq6naF">
  <SignedInfo>
    <CanonicalizationMethod Algorithm="http://ift.tt/y9fQ1c"/>
    <SignatureMethod Algorithm="http://ift.tt/zf1Wx4"/>
    <Reference URI="">
      <Transforms>
        <Transform Algorithm="http://ift.tt/A1C4L2"/>
      </Transforms>
      <DigestMethod Algorithm="http://ift.tt/1jbsD3O"/>
      <DigestValue>IssCQWd+dCUvTL9QuVgE/TzecC3wSbzQQ71CLrjpJGQ=</DigestValue>
    </Reference>
  </SignedInfo>
  <SignatureValue>COI61D+lQ1lLJ17wIBKr+O2kV4au97BMqM+EVPePw6g/itAq4UGBueGhANvYvElzyQcd12dTyh3QUhh/4rUorP6PXuO6eF6f9m13h3rRUupgeKaQbE65j1uvOGj1uXqMoNEuNHSUatATBkXJlfg3PCQfKyywHmW2GTtSKsvfj7WaQ7X9qnJMaCJXdOFS7eEFZ5C9KIutxIKRrH+YsaibwkVOfBYoVNVF08PjUfEpUMHCL6+z2WedRSwLxDPe0ByAN3eLsqGfVOLPSXvB7q3Y+sjE9cE5+vIxHlKhNzlYYayaY0B8Txa79b/g2Rl3fcajKHqVH+FD2lGFVdfktrksjg==</SignatureValue>
  <KeyInfo>
    <KeyValue>
      <RSAKeyValue>
        <Modulus/>
        <Exponent/>
      </RSAKeyValue>
    </KeyValue>
  </KeyInfo>
</Signature>
</note>

But 3rd party service return SIGNATURE MISMATCHING when posting above XML payload. I think issue is due to Modulus and Exponent are missing from output.xml.

My question is how to generate Modulus and Exponent?

samedi 28 octobre 2017

React.js update state property to a new object

After componentDidMount quote is equal to {id: 16, text: "Be yourself; everyone else is already taken.", author: "Oscar Wilde", next_id: 18, previous_id: null}

When I click next, componentWillRecieveProps is invoked and tries to update quote to another object. I get an error. the same if I try to change it to a string. But when I try to change quote to a number or boolean, it works.

componentDidMount() {
  this.fetchQuote(16)
}

fetchQuote(id) {
  axios.get(`api/quotes/${id}`)
  .then(response => {
    console.log("Data: ", response.data);
    this.setState({
      quote: response.data
    }, ()=> {console.log("fetch: ", this.state);})
  })
  .catch(error => {
    console.error(error)
    this.setState({ fireRedirect: true })
  })
}

componentWillReceiveProps(nextProps) {
  this.qsParams = queryString.parse(nextProps.location.search)
  this.quoteId = Number(this.qsParams.quote)
  this.fetchQuote(this.quoteId)

}

componentWillReceiveProps(nextProps) successful triggers fetchQuote and that function makes a request and gets right data which is an object, but can't change quote to that received data

React-on-Rails: Error when updating state in axios request

I'm debugging a code which was written by someone else. In componentDidMount() i'm sending an axios request and updating the state. render() renders data successfully.

But after clicking next button I need to make another axios request, update the state and render new data. I use componentWillReceiveProps(nextProps) for that. I successfully make axios request, it's returning correct data, but it doesn't want to change state, it throws several errors instead. How can I fix it?

componentWillReceiveProps(nextProps) {
  this.qsParams = queryString.parse(nextProps.location.search)
  this.quoteId = Number(this.qsParams.quote)

  axios.get(`api/quotes/${this.quoteId}`)
  .then(response => {
    console.log("Data: ", response.data); // prints correct data
    this.setState({ //not being invoked, throws errors
      quote: response.data
    }, ()=> {console.log("fetch: ", this.state);})
  })
  .catch(error => {
    console.error(error)
    this.setState({ fireRedirect: true })
  })
}

"554 Please activate your Mailgun account. Check your inbox or log in to your control panel to resend the activation email." error Ruby on Rails

I am building a web app using Ruby on Rails. I am using Mailgun as my mailer for this app. when i sign up using Facebook it works fine but when i try to sign up using email and password , i keep getting this error "554 Please activate your Mailgun account. Check your inbox or log in to your control panel to resend the activation email." I have already authorized the eamil to the Authorized Recipients in mailgun dashboard. Here's my code:

Registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController
  protected
    def update_resource(resource,params)
      resource.update_without_password(params)
    end
end

config/environments/development.rb

 Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # In the development environment your application's code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports.
  config.consider_all_requests_local = true

  # Enable/disable caching. By default caching is disabled.
  if Rails.root.join('tmp/caching-dev.txt').exist?
    config.action_controller.perform_caching = true

    config.cache_store = :memory_store
    config.public_file_server.headers = {
      'Cache-Control' => 'public, max-age=172800'
    }
  else
    config.action_controller.perform_caching = false

    config.cache_store = :null_store
  end

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = true

  config.action_mailer.perform_caching = false

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations.
  config.active_record.migration_error = :page_load

  # Debug mode disables concatenation and preprocessing of assets.
  # This option may cause significant delays in view rendering with a large
  # number of complex assets.
  config.assets.debug = true

  # Suppress logger output for asset requests.
  config.assets.quiet = true

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true

  # Use an evented file watcher to asynchronously detect changes in source code,
  # routes, locales, etc. This feature depends on the listen gem.
  config.file_watcher = ActiveSupport::EventedFileUpdateChecker

  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
  address: 'smtp.mailgun.org',
  port: 587,
  domain: 'sandboxc77c3a9be90a494081dad1628d554337.mailgun.org',
  authentication: 'plain',
  user_name: 'postmaster@sandboxc77c3a9be90a494081dad1628d554337.mailgun.org',
  password: 'password'
}


end

initalizers/devise.rb

      # If true, requires any email changes to be confirmed (exactly the same way as

      config.reconfirmable = false

  config.mailer_sender = 'ahmed @ iGloo <no-reply@igloo.com>'

views/devise/registrations/new.html.erb

<div class="row">
  <div class="col-md-4 col-md-offset-4">
<h2>Sign up</h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= render 'layouts/shared/devisemes' %>

    <div class="form-group">
    <%= f.text_field :fullname, autofocus: true , placeholder: "Full Name" , class: "form-control" %>
  </div>

  <div class="form-group">
    <%= f.email_field :email, autofocus: true , placeholder: "Email" , class: "form-control" %>
  </div>

  <div class="form-group">
    <%= f.label :password %>
    <% if @minimum_password_length %>
    <em>(<%= @minimum_password_length %> characters minimum)</em>
    <% end %><br />
    <%= f.password_field :password, autocomplete: "off" , placeholder: "Password" , class: "form-control" %>
  </div>



  <div class="actions">
    <%= f.submit "Sign up" , class: "btn btn-normal btn-block" %>
  </div>
<% end %>

<%= link_to "Sign up with Facebook", user_facebook_omniauth_authorize_path , class: "btn btn-facebook btn-block"%>


<%= render "devise/shared/links" %>
</div>
</div>

vendredi 27 octobre 2017

Dynamically passing of parameter in rails sql query

Below is an SQL query which fetches some data related to user.

def self.get_user_details(user_id)

      result = Event.execute_sql("select replace(substring_index(properties, 'text', -1),'}','') as p, count(*) as count
                  from ahoy_events e where e.user_id = ?
                  group by p order by count desc limit 5", :user_id)

      return result
 end

I want to dynamically pass values to user id to get the result. I am using the below method to sanitize sql array, but still it returns no result. The query works fine if given static parameter.

   def self.execute_sql(*sql_array)     
       connection.execute(send(:sanitize_sql_array, sql_array))
    end

Because the query is complicated I am couldn't figure out the ActiveRecord way to get the results. Is there any way I could get this sorted out?

Rails - Refreshing ajax partial that contains nested array returns undefined method error

I have two models;

class Course < ActiveRecord::Base
  has_permalink :name, :unique => true

  has_many :courselocations
  accepts_nested_attributes_for :courselocations
end

class Courselocation < ActiveRecord::Base
  has_permalink :urlname, :unique => true

  belongs_to :courses
end

In my Course > Edit view, I'm calling a partial that loops through all the associated courselocations for that course. The user can edit each courselocation and update via ajax.

Admin > Courses > Locations Partial

  <div class="row marginBottom40">
    <% @course.courselocations.each do |location| %>
    <div class="padAll20 ghostBorder borderBox col-lg-3 colMarginRight whiteBG col">
      <h3 class="marginBottom10"><%= location.name %></h3>
      <div class="small-text"><%= location.city %>, <%= location.state %></div>
      <ul class="marginTop20 stretch"  style="    flex: 1 0 auto;">
        <li><h4 class="marginBottom10">Instructors</h4></li>
        <% for s in location.coursesessions %>
          <% if s.courseinstructor_id.nil? %>
            <p>Add instructors by <%= link_to "managing", "/admin/courses/#{@course.permalink}/courselocations/#{location.permalink}/edit", :class => 'displayBlock', :remote => true, :id => "#{location.id}_link" %> the course location</p>
          <% else %>
            <li class="marginBottom20 teachers row">
              <div class="col-lg-3 selfCenter">
                <%= cl_image_tag s.courseinstructor.image_url(:profileSmall), :class => "image" %>
              </div>
              <div class="col-lg-9">
                <%= s.courseinstructor.first_name %> <%= s.courseinstructor.last_name %>
                <div class="small-text"><%= s.courseinstructor.title %></div>
                <div class="small-text"><%= s.courseinstructor.company %></div>
              </div>
            </li>
          <% end %>
        <% end %>
        <li><h4 class="marginBottom20">Dates</h4></li>
        <li>
          <% for d in location.coursedates %>
            <span class="padAll10 grayBG inlineBlock"><%= d.start.strftime('%b %d, %y') %></span>
          <% end %>
        </li>
      </ul>
      <div class="padTop20 col-lg-end">
        <%= link_to "Manage", "/admin/courses/#{@course.permalink}/courselocations/#{location.permalink}/edit", :class => 'block btn btn-outline', :remote => true, :id => "#{location.id}_link" %>
      </div>
    </div>
    <% end %>
  </div>

Admin > Courselocations > Update.js.erb

$(document).ajaxSuccess(function(event, request) {
  $("#edit_location").empty();
  $('#locationData').slideDown('slow').after('');
});
$('#locations').html("<%= j render(partial: '/admin/courses/locations', locals: {location: @course.courselocations}) %>");

The problem however is that on update, I get a NoMethodError in Admin::Courselocations#update ... undefined method 'courselocations' for nil:NilClass

I'm assuming that since I'm calling the edit view remotely from courselocation that Rails doesn't understand what @course.courselocations is but I'm not sure how to solve this issue.

why & is not accepting rails 3

why "&" is not accepting in jquey in rails application.It's showing name does't exits.please help me

Actually my model having data like ="TAJ MALL & LIMITED" But query is running

SELECT "employers".* FROM "employers" WHERE (lower(name) = 'TAJ MALL') LIMIT 1

Regards, Srikanth

jeudi 26 octobre 2017

Rspec return No route matches when using scoped route

I have a route that is defined as this in my routes.rb as so

scope ':prefix', as: :foo, controller: 'foo_paths', action: :placeholder do
  get 'foo/:id', as: 'result'
end

The issue is when running my test it always returns

 Failure/Error: subject { get :placeholder }

 ActionController::UrlGenerationError:
   No route matches {:action=>"placeholder", :controller=>"foo_paths"}

Here's all my code I can't find any error everything works fine in the browser and rake routes return the expected route.

foo_paths_controller.rb

class FooPathsController < ApplicationController
  def placeholder
    render nothing: true, status: :service_unavailable
  end
end

foo_paths_controller_spec.rb

describe FooPathsController, type: :controller do
  describe "GET 'placeholder'" do
    subject { get :placeholder }

    it 'renders an empty page with service unavailable http error' do
      subject

      it { expect(subject).to have_http_status(503) }
      it { expect(subject.body).to be_blank }
    end
  end
end

rake routes

foo_result GET      /:prefix/foo/:id(.:format)                                                            foo_paths#placeholder

Ruby on rails 3 - Using checkbox field inside form_for , sending html and json both request in ajax call

I have toggle button on my form and on toggling it i am sending ajax call request to save updated boolean value in the database from controller. but it is sending Html and json request both. I just want to send only one json request. (using rails 3.*)

post_as_premium.html.erb

<%= form_for @editor, url: set_as_premium_reporter_path, remote: true do |f| %>
<div class="editorSettings">
      <div class="premiumCheck">
        <label class="clearfix" for="user_post_premium_permission">
          <span class="checkBoxWrap <%= @editor.post_premium_permission ? 'allChecked' : '' %>">
            <%= f.check_box :post_premium_permission %>
          </span>
        </label>
      </div>
  </div>
<% end %>
     <script type="text/javascript">
        if($("#user_post_premium_permission").parent("span").hasClass('allChecked')){
            $("#user_post_premium_permission").attr('checked', true);
        }else{
            $("#user_post_premium_permission").attr('checked', false);
        }

        $("#user_post_premium_permission").on("change", function(){
            if ($(this).prop('checked')){
                $(this).parent("span").addClass("allChecked");
            }else{
                $(this).parent("span").removeClass("allChecked");
            }
            this.form.submit();
        });
  </script>

2 ] Controller -

 def post_as_premium
   @editor = current_user
 end

def set_as_premium
if params[:editor] && params[:user][:post_premium_permission]
  current_user.update_attributes(post_premium_permission: params[:user][:post_premium_permission])
  respond_to do |format|
    format.js { head :ok }
    format.html { redirect_to post_as_premium_path(current_user)}
  end
end

Rails 4 - ensure has_many associated objects (integer) start at 0 and have no "gap" in the incremental values

I have two models sharing a has many/belong to relations

A Deal has_many Steps.

Each step as an attribute called "Appearance Order" which define when it appears (different than the id).

It's an integer that I validate is >= 0 and <15

I input the Steps directly in Active Admin's Deal edition thanks to:

accepts_nested_attributes_for :steps, allow_destroy: true

I already have in place a validation that ensures that there can't be one Step belonging to the same Deal and sharing the similar 'Appearance Order' thanks to:

validates :appearance_order, uniqueness: { scope: [:deal_id] }

But today, A Deal where the various associated Steps would have as 'Appearance Order" 1, 5, 7,14 would be accepted. I need to find a validation that reject that case.

On the Deal model I need validations that ensure:

  • among one deal(id:4).steps (steps associated with the Deal) , there is at least one with the 'Appearance Order' equal to 0

  • then the deal(id:4).steps' 'Appearance order' have no "gap" between each of their value. It must be 0,1,2,3,4,....and so on.

For example if I create a Deal with 4 Steps who have 'Appearance Order' attribute of 0,1,2,5 should be rejected because there is a gap between 2 and 5.

Here is my code:

models/step.rb

class Step < ActiveRecord::Base
  belongs_to :deal,             :foreign_key => 'deale_id'
   validates :appearance_order,
              presence: true,
              numericality: { greater_than_or_equal_to: 0,
                              less_than_or_equal_to: 14}

   validates :appearance_order, uniqueness: { scope: [:deal_id] }
end

models/deal.rb

class Deal < ActiveRecord::Base

  has_many   :steps,          dependent:  :destroy do   
    # source: http://ift.tt/2jhaYEm
    def length
      reject(&:marked_for_destruction?).length
    end
  end 

  validates :steps, length: { maximum: 15 }

end

mercredi 25 octobre 2017

Rails server saying rollback transcation when clicking add to cart

Just started learning ruby on rails, and i created a simple shopping cart application but when i click "add to cart", i get a rollback transaction from my server. I believe the error has something to do with my orderitem controller but not sure how to fix this issue here my code.


rails server

Started POST "/order_items" for 127.0.0.1 at 2017-10-25 10:47:44 -0400
Processing by OrderItemsController#create as JS
  Parameters: {"utf8"=>"✓", "order_item"=>{"product_id"=>"13", "quantity"=>"1"}, "commit"=>"Add to cart"}
   (0.0ms)  begin transaction
  Product Load (0.5ms)  SELECT  "products".* FROM "products" WHERE "products"."id" = ? LIMIT ?  [["id", 13], ["LIMIT", 1]]
   (0.0ms)  rollback transaction
  Rendering order_items/create.js.erb
  Rendered order_items/create.js.erb (0.5ms)
Completed 200 OK in 1028ms (Views: 605.5ms | ActiveRecord: 0.5ms)


order_items_controller.rb

class OrderItemsController < ApplicationController

    def create
        @order = current_order
        @order_item = @order.order_items.new(order_item_params)
        @order.save
        session[:order_id] = @order.id
    end

    def update
        @order = current_order
        @order_item = @order.order_items.new(order_item_params)
        @order_item.update_attributes(order_item_params)
        @order_items = @order.order_items
    end

    def destroy
        @order = current_order
        @order_item = @order.order_items.find(params[:id])
        @order_item.destroy
        @order_items = @order.order_items
    end


    private

    def order_item_params
        params.require(:order_item).permit(:product_id, :quantity)
    end

end


create.js.erb

<% if @order.errors.any? || @order_item.errors.any? %>
    alert("Invalid")
<% else %>
    $(".cart").html("<%= escape_javascript(render 'layouts/cart') %>")
<% end %>


schema.rb

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

  create_table "order_items", force: :cascade do |t|
    t.integer  "product_id"
    t.integer  "order_id"
    t.integer  "quantity"
    t.float    "total_price"
    t.float    "unit_price"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  create_table "orders", force: :cascade do |t|
    t.float    "subtotal"
    t.float    "total"
    t.float    "shipping"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "user_id"
  end

  create_table "products", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.float    "price"
    t.text     "description"
    t.string   "picture"
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.string   "username"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

end

Capybara test case for Login page authentication

I have capybara test case below.

it "Testing login page with valid data" do
  fill_in 'email', with: 'kiran@gmail.com'
  expect(page).to have_selector("input[value='kiran@gmail.com']")#Checking values are inserted in email field

  fill_in 'password', with: 'Kiran.6565'
  expect(page).to have_selector("input[value='Kiran.6565']")#Checking values are inserted in password field

  click_button('submit')

  expect(current_path).to eql(patient_detail_path(4))

end

I am checking Login page once the email and password fields are matches it should redirect to patient_details_path with id field value. In above code i specified email and password is working fine for manual login, but problem is in test case. Expected result: it should redirect to another page(patient_details_path) but it redirecting to home page(/) again.

Failures:

1) Login Page Interface Test login page with valid data
   Failure/Error: expect(current_path).to eql(patient_detail_path(4))

   expected: "/patient_details/4"
        got: "/"

   (compared using eql?)
 # ./spec/views/login_spec.rb:41:in `block (2 levels) in <top (required)>'

Finished in 1.08 seconds (files took 2.13 seconds to load)
14 examples, 1 failure

I tried different solution's from stackoverflow but nothing work for me. Below are the different solution's tried.

#expect(current_path).to eql(patient_detail_path(4))
#expect(page).to have_current_path(patient_detail_path(4))

If email and password mismatch it will throw an error and redirect to login page again. In my scenario it was throwing an error even if email and password are valid . If i add below code in my test case it will work pass the test case.

#expect(page).to have_content "Invalid username/password combination"

Any one please help me i am new to ruby on rails and capybara.

mardi 24 octobre 2017

flash messages in rails using turbolinks

I used turbolinks in my Rails 5 app. Now it is behaving as single page app which is good. But when I create a new user or sign up the flash errors are not showing up. In console there are errors but I need to show them using flash errors. Any suggestions would be very helpful. Thanks in advance.

POST http://localhost:3000/users/sign_in 401 (Unauthorized)
Rails.ajax @ rails-ujs.self-817d9a8cb641f7125060cb18fefada3f35339170767c4e003105f92d4c204e39.js?body=1:189
Rails.handleRemote @ rails-ujs.self-817d9a8cb641f7125060cb18fefada3f35339170767c4e003105f92d4c204e39.js?body=1:546
(anonymous) @ rails-ujs.self-817d9a8cb641f7125060cb18fefada3f35339170767c4e003105f92d4c204e39.js?body=1:146
VM707:1 Uncaught SyntaxError: Unexpected identifier
    at processResponse (rails-ujs.self-817d9a8cb641f7125060cb18fefada3f35339170767c4e003105f92d4c204e39.js?body=1:246)
    at rails-ujs.self-817d9a8cb641f7125060cb18fefada3f35339170767c4e003105f92d4c204e39.js?body=1:173
    at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.self-817d9a8cb641f7125060cb18fefada3f35339170767c4e003105f92d4c204e39.js?body=1:23

Comment .XML file content from ruby code

Can anyone tell me how can I comment following line on my .XML file by using ruby code.

I hope this can be done by using "nokogiri". but I'm just new to the ruby. any help would be much appreciated.

<message group="1" sub_group="1" type="none" destination="mydata" remark="mylist" userOnly="true "/>

output should be:

<!-- <message group="1" sub_group="1" type="none" destination="mydata" remark="mylist" userOnly="true "/> -->

lundi 23 octobre 2017

Remove records from has_many Rails association with a single query

I'm having trouble removing records from a has_many association in Rails without triggering unnecessary queries. Essentially, I have a model which has a has_many relation on it, and I want to remove multiple records from it based on some criteria. I want to be able to simultaneously keep the association up to date, but also remove the records from the database, and only require one DELETE query to do this. I've tried assigning to the relation with the new objects (which generates unnecessary UPDATE queries) and calling delete_all (which makes one query but doesn't update the association).

create_relation vs Relation.create - Minitest failing on first option

I'm having an odd issue and I'm not sure what is going on, so looking for some clarity. I have a model, let's call it Parent, and Parent has a child relationship called Child. Currently, my code is setup like this:

@parent = Parent.new(@parent_attributes)
if (@parent.save)
   @parent.create_child
end

This code resides in a service, and works just fine and dandy when running the app normally through the controller.

But when I try to test the service directly, this code fails, with null exception that the parent_id isn't set. The parent has_one :child, inverse_of: :parent and the child belongs_to :parent, inverse_of :child

The thing that makes no sense to me, is that if I change the above code to:

if (@parent.save)
   @parent.child = Child.create
end

the test works just fine. Can anyone explain to me why this would be?

How to adjust Controller so ordering the table by prename works in ruby on rails

Rails noob here. I would like to know why the order function does not work when you not searched for a person using the search function. The user can click on the table head prename and the table should be ordered asc or desc. There is also a search function on this page. When you search for a person and there are like 1+ results, here the ordering works. But it does not work when you have not searched for a person.

Tables

  • person has_many :participants
  • participant belongs_to person

When you visit the page the persons are ordered by the frequency of the participants.

PersonsController

if params[:search_me]
     @persons = Person.search_me(params[:search_me]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 5, :page => params[:page])
else
 @persons = Person.select('persons.*, count(participants.person_id) AS participant_count').joins(:participants).group('participants.person_id').order('participant_count desc').paginate(:per_page => 30, :page => params[:page]).order(sort_column + ' ' + sort_direction)
end

private

def sort_column
   Person.column_names.include?(params[:sort]) ? params[:sort] : "prename"
end

def sort_direction
   %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end

Person View

<%= will_paginate @persons, :previous_label => t("previous_label"), :next_label => t("next_label"), :page_gap => t("will_paginate.page_gap")%>

Thank you in advance

dimanche 22 octobre 2017

Rails 4 - Using Transactions along with Begin rescue block

i have a piece of code which is used to do following things triggered from a controller call.i am using Rails Transaction along with begin/rescue end block to make the below series of code execution more robust.Its as shown below:-

  1. Save the object
  2. save the associations and update the attribute value
  3. send email
  4. send text message
  5. redirect

    ###in my controller 
     def verify   
        @request=Request.includes(:user).find(params[:id])
        @request.transaction do
          begin
            if @request.accepted?
               ##this method will call more 3 methods in the request model
               @request.send_email_and_sms
               flash[:success] = "Request is moved to another state"
            else
              flash[:error] = "Request was not accepted and couldn't be moved to another state"
            end        
          rescue
            flash[:alert] = "There was some internal error.Kindly debug"
          ensure
            @request.reload
            Rails.logger.info "================Making GO AHEAD TOKEN FALSE AND DEACTIVATE VENUE====================#{@request.attributes}==========="
            redirect_to request_hall_path(@request.user)
          end      
        end    
      end
    
    

    `

Is this the correct way to ensure that every piece of code will execute else it will jump on rescue with the flash.alert message.

Is there any other way that i am missing to make this code/logic more full proof and robust.

Thanks in advance.

samedi 21 octobre 2017

how to create GUI in ruby based on the code given?

This is the simple code I've written in ruby that will access to a rest server via HTTP methods.

class Rest_client

def get_method (host, path)
require 'net/http'
uri = URI.parse("#{host}")
http=Net::HTTP.new(uri.host,uri.port)
request = Net::HTTP::Get.new("#{path}")
reply=http.request(request)
puts "#{reply.code} #{reply.message}"
reply.header.each_header {|key,value| puts "#{key} = #{value}" } 
puts "#{reply.body}"

end

end
ARGV[2] == 'GET'
rc=Rest_client.new
rc.get_method(ARGV[0],ARGV[1])

How to write above mentioned code in GUI format based on this image ?I'm totally new in ruby and GUI, please guide me on how to do this.

Besides that, One of the criteria is the get button command proc should initialize these 4 things

  • connect to host using Rest_client
  • object get the method using Rest_client
  • Get the response using Rest_client
  • Update the label and text fields

Cant update relations on Update action in rails controller

When updating a resource called JobsI want to copy some of the values from this update to some resources connected to this resource

Jobs has many Hours each hour has a period with 2 set of times. So if i update the job with these times i want them copied down to the periods

I tried this code in different variants but the periods entities dont get updated.

  def update
@job = Job.find(params[:id])

respond_to do |format|
  if @job.update_attributes(params[:job])

    @job = Job.find(params[:id])

    @job.hours.each do |hour|
      logger.debug params[:job][:start1]
      logger.debug params[:job][:end1]
      hour.periods.first.start_time = params[:job][:start1]
      hour.periods.first.end_time = params[:job][:end1]
      hour.periods.last.start_time = params[:job][:start2]
      hour.periods.last.end_time = params[:job][:end2]
    end

    @job.save

    format.html { redirect_to @job, notice: 'Job was successfully updated.' }
    format.json { head :no_content }
  else
    format.html { render action: "edit" }
    format.json { render json: @job.errors, status: :unprocessable_entity }
  end
end

end

vendredi 20 octobre 2017

Carrierwave filename method creating issue when uploading file to s3

I have an ImageUploader. And want to upload image into S3. Also change filename using filename method. Here the code:

class ImageUploader < CarrierWave::Uploader::Base

storage :fog

  def store_dir
    "images"
  end

  def filename
    "#{model.id}_#{SecureRandom.urlsafe_base64(5)}.#{file.extension}" if     original_filename
  end
end

First time when I save an image to model then it will give correct filename e.g 1_23434.png

But when I get the model object from the terminal console then it will return different image name and changed image name.

Is there anyone here who can tell me what I do? It works fine when I do not use fog.

Spree - Products per page to be made dynamic

Spree - Products per page to be made dynamic: How to set the product per page to be dynamic? Thanks in Advance

#Products_controller 

module Spree
class ProductsController < Spree::StoreController
before_filter :load_product, :only => :show
before_filter :load_taxon, :only => :index

rescue_from ActiveRecord::RecordNotFound, :with => :render_404
helper 'spree/taxons'

respond_to :html

def index
  @searcher = build_searcher(params)
  @taxonomies = Spree::Taxonomy.includes(root: :children)
  @products = Product.page(params[:page]).per(3)
end

def show
  return unless @product

  @variants = @product.variants_including_master.active(current_currency).includes([:option_values, :images])
  @product_properties = @product.product_properties.includes(:property)
  @taxon = Spree::Taxon.find(params[:taxon_id]) if params[:taxon_id]
end

private
  def accurate_title
    @product ? @product.name : super
  end

  def load_product
    if try_spree_current_user.try(:has_spree_role?, "admin")
      @products = Product.with_deleted
    else
      @products = Product.active(current_currency)
    end
    @product = @products.friendly.find(params[:id])
  end

  def load_taxon
    @taxon = Spree::Taxon.find(params[:taxon]) if params[:taxon].present?
  end
 end
end

Spree - Products per page to be made dynamic

How to set the product per page to be dynamic?

Thanks in Advance

mercredi 18 octobre 2017

How to execute a private method after a model update?

I have created a private method inside a controller.

private
def update_mark
...
...
end

  • I want my private method to be called whenever record gets updated to any of the four Models we have. How can we do this ?

uninitialized method first_name using fixy gem

I am using this gem to help me in making fixed file formatters. I am following the documentation but getting an error

require('fixy')
class Record < Fixy::Record
  include Fixy::Formatter::Alphanumeric
  # Define record length
  set_record_length 20

  # Fields Declaration:
  # -----------------------------------------------------------
  #       name          size      Range             Format
  # ------------------------------------------------------------

  field :first_name,     10,     '1-10' ,      :alphanumeric
  field :last_name ,     10,     '11-20',      :alphanumeric

  # Any required data for the record can be
  # provided through the initializer

  def initialize(first_name, last_name)
    @first_name = first_name
    @last_name  = last_name
  end

  # 2) Using a method definition.
  #    This is most interesting when complex logic is involved.
  def last_name
    @last_name
  end
end

shinken =  Reky.new('Sarah', 'Smith')
p shinken.generate

The last method: shinken.generate gives the error: generate': undefined methodfirst_name' for # (NoMethodError)

What may be causing this?

Rollback gems according to version in Gemfile.lock

I need to revert back to an older set of gem's in my dev environment. I've replaced my Gemfile.lock file with the old versions I need.

I thought I could just replace the Gemfile.lock and bundle install but that doesn't seem to work. Because when I do that and then run bundle install and then check the gem version number I get the same versions I had before.

One of the gems I need to downgrade is the rake gem. The version I need is 11.1.2 but currently when I do gem list I get rake (12.0.0, 11.1.2, 10.4.2)

So how can I revert rake and all the other gems, back to their previous versions?

displaying rails index view files with a list from database

I have a rails index view file displaying a list of projects that have been created. I originally added some logic hoping that the page will display both with an empty projects table or a projects table with a populated database. However I am not getting the expected results.

index.html.erb

<div class="container">
  <div class="row">
    <div class="well projects">
      <h1>Projects</h1>
      <h2><%= link_to 'New Project', new_project_path, class: 'btn btn-default' %></h2>

      <table class="table table-striped">
        <% if Project.exists?(current_account) %>
          <% @project.each do |project| %>
            <tr>
              <td><%= link_to project.title, project_tasks_path(project) %></td>
              <td><%= project.details %></td>
            </tr>
          <% end %>
        <% end %>
      </table>
    </div>
  </div>
</div>

application_controller.rb

def current_account
  @current_account ||= User.find_by(subdomain: request.subdomain)
end

projects_controller.rb - index action

def index
    @project = current_account.user_projects
end

If I remove the code <% if Project.exists?(current_account) %> and try running the page with an empty projects table, I receive the following error:

NoMethodError in Users::Projects#index
undefined method `title'

If I run the page with the code <% if Project.exists?(current_account) %> it provides a depreciation warning in the console. Also, It doesn't populate the list as expected, In some cases not populating the records and leaving a blank list even though some exist.

undefined method `count' for nil:NilClass rails

i am trying to have a photo upload section in my room listing. when i try to click on the photos i get this error undefined method `count' for nil:NilClass rails <% if @photos.count > 0 %> . i have added a photo_upload.html.erb page and a _room_menu partial but still i get the error.

here's my code:

photos_controller.rb

       class PhotosController < ApplicationController
        def create
          @room = Room.find(params[:room_id])
          if params[:images]
            params[:images].each do |img|
              @room.photos.create(image:img)
            end
            @photos = @room.photos
            redirect_back(fallback_location:request.referer, notice: "Saved...")
        end
      end


    end

**views/rooms/photo_upload.html.erb**

<div class="row">
  <div class="col-md-3">
    <%= render 'room_menu' %>
  </div>
  <div class="col-md-9">
    <div class="panel panel-default">

      <div class="panel-heading">
        Photos
      </div>

      <div class="panel-body">
        <div class="container">
          <div class="row">
            <div class="col-md-offset-3 col-md-6">
              <!-- PHOTOS UPLOAD GOES HERE -->

              <%= form_for @room, url: room_photos_path(@room), method: 'post', html: {multipart: true} do |f| %>
                <div class="row">
                  <div class="form-group">
                    <span class="btn btn-default btn-file text-babu">
                      <i class="fa fa-cloud-upload" aria-hidden="true"></i> Select Photos
                      <%= file_field_tag "images[]", type: :file, multiple: true %>
                    </span>
                  </div>
                </div>

                <div class="text-center">
                  <%= f.submit "Add Photos", class: "btn btn-form" %>
                </div>

              <% end %>
            </div>
          </div>

          <div id="photos"><%= render 'photos/photos_list' %></div>
        </div>
      </div>

    </div>
  </div>
</div>

views/rooms/_room_menu.html.erb

<ul class="sidebar-list">
  <li class="sidebar-item">
    <%= link_to "Listing", listing_room_path, class: "sidebar-link active" %>
    <span class="pull-right text-babu"><i class="fa fa-check"></i></span>
  </li>
  <li class="sidebar-item">
    <%= link_to "Pricing", pricing_room_path, class: "sidebar-link active" %>
    <% if !@room.price.blank? %>
      <span class="pull-right text-babu"><i class="fa fa-check"></i></span>
    <% end %>
  </li>
  <li class="sidebar-item">
    <%= link_to "Description", description_room_path, class: "sidebar-link active" %>
    <% if !@room.listing_nam.blank? %>
      <span class="pull-right text-babu"><i class="fa fa-check"></i></span>
    <% end %>
  </li>

    <li class="sidebar-item">
    <%= link_to "Photos", photo_upload_room_path, class: "sidebar-link active" %>
    <% if !@room.photos.blank? %>
      <span id="photo_check" class="pull-right text-babu"><i class="fa fa-check"></i></span>
    <% end %>
  </li>

  <li class="sidebar-item">
    <%= link_to "Amenities", amenities_room_path, class: "sidebar-link active" %>
    <span class="pull-right text-babu"><i class="fa fa-check"></i></span>
  </li>
  <li class="sidebar-item">
    <%= link_to "Location", location_room_path, class: "sidebar-link active" %>
    <% if !@room.address.blank? %>
      <span class="pull-right text-babu"><i class="fa fa-check"></i></span>
    <% end %>
  </li>
</ul>
<hr/>

mardi 17 octobre 2017

NameError Exception: uninitialized constant BCrypt Rails 5, Windows

I am using Devise with Rails 5 on Windows. I know about the problem with Windows and BCrypt and I am following the instructions from internet to make it work:

  1. uninstall all bcrypt gem versions with gem uninstall bcrypt and select option 3 (if exist);
  2. gem uninstall bcrypt-ruby and select option 3 (if exist);
  3. install bcrypt using gem install bcrypt --platform=ruby;
  4. add this line gem 'bcrypt', platforms: :ruby to Gemfile.

And I thinks it works, because Devise depends on BCrypt and Devise works fine.

The problem is when I use Byebug and use in the console BCrypt, I am getting an error:

NameError Exception: uninitialized constant Auth::AuthController::BCrypt

For the exaample if I type: BCrypt::Engine.generate_salt I am getting the error.

lundi 16 octobre 2017

Can we call a controller method inside rake tasks...?

Is there any way by which controller methods can be used inside Rake task.

rails 3 making an API call when view is not open

My app is making twitter API calls. I call the function in my view and added in beginning of the view (index.htnl.erb):

 <head>
  <meta http-equiv="refresh" content="60">  <!-- update every 1mn -->
</head>    

So that the page is refreshed every minute and I can collect infos for my DB from the API call. I did not want to refresh all the views just this one (index.htnl.erb).
How can I have my function called the API when the index page is not open?

Check is it valid reset_password_token, Rails 5 devise

I am using Rails 5 with Devise. I want when some1 make request for new password, then go to the URL to change his password, if it is not valid reset_password_token to return 404:

unless confirm_token.errors.empty?
  raise ActionController::RoutingError.new('Not Found')
end

For this I need to check is it GET parameter reset_password_token same as one in the table column reset_password_token.

There is a method for that confirm_by_token, but it is for validate email URL and checks column 'confirmation_token'. Is there build in Devise method for checking is it valid reset_password_token or I need to create it ?

Dynamic transition for statesman gem

I am using rails 3.2, My application needs a finite state machine whereas, the finite state transition flow will be configured by the users and stored in db. How can I fetch the dynamic state transition from db and set it for statesman's class to work.

Thanks in advance

dimanche 15 octobre 2017

Same route name for POST, GET PUT, PATCH, Rails 5

I am using Devise and change its default routes like this:

devise_for :users, :path => '',skip: [:sessions]

as :user do
    get '/forgotten' => 'users/passwords#new', as: :password
    post '/forgotten' => 'users/passwords#create'
    put '/forgotten' => 'users/passwords#update'
    get '/password/edit' => 'users/passwords#edit'
end

The generated URL (form action attribute) for new.html.erb (view for sending email with new password instructions) is /forgotten.user, which is not correct. The correct URL is /forgotten and it is used with different HTTP verbs GET/POST/PUT. In request new password form (new.html.erb):

<%= form_for(resource, as: resource_name, 
             url: password_path(resource_name), html: { method: :post}) 

Without my custom routes with rake routes, I see for these routes:

user_password | PATCH | /password(.:format) | users/passwords#update

PUT | /password(.:format) | users/passwords#update

POST | /password(.:format) | users/passwords#create

How to make this route custom and used for different HTTP verbs ?

Change default routes Devise Rails

I have this routes.rb:

  devise_for :users, :path => '', path_names: 
                          { sign_in: "login", sign_out: "logout", sign_up: "registration"}

I changed sign_in and sign_up routes and if you go to sign_up you will get 404 error, instead /registration will work. What I want is to change and another routes like forgotten password in the same way. If I type in the console rake routes, I see this for forgotten password:

new_user_password GET /password/new(.:format) devise/passwords#new

How can I do that, but and make default route to not work, just the new one?

Connection timeout for SOCKSProxy Calls in resque Rails production mode

i have simple background job that runs using resque-pool which makes certain socksproxy call. This works fine when i start the resque-pool in Rails development mode as soon as i change to production mode i hit connection timeout with background job

The same code works when executed in

  • Rails Console in Production mode
  • Standalone ruby script invoked from command line

calls are something like:

req = Net::HTTP::Get.new(uri.request_uri)
response = Net::HTTP.SOCKSProxy(@socks_server, @socks_port).start(uri.host, uri.port) do |http|
    http.request(req)
end

Investigation:

when this call happens in net/http.rb

TCPSocket.open(conn_address, conn_port, @local_host, @local_port)

i found that in production mode worker child process instead of loading TCPSocket class from socksify-1.7.0/lib/socksify.rb it is still loading from ruby provided resolv-replace.rb. Not sure why though.

Error i see:

Connection timed out - connect(2) for "" port 6455: /usr/lib/ruby/gems/2.1.0/gems/socksify-1.7.0/lib/socksify.rb:178:in initialize' /usr/lib/ruby/gems/2.1.0/gems/socksify-1.7.0/lib/socksify.rb:178:in initialize' /usr/lib/ruby/2.1.0/resolv-replace.rb:23:in initialize' /usr/lib/ruby/2.1.0/net/http.rb:879:inopen' /usr/lib/ruby/2.1.0/net/http.rb:879:in block in connect' /usr/lib/ruby/2.1.0/timeout.rb:76:intimeout' /usr/lib/ruby/2.1.0/net/http.rb:878:in connect' /usr/lib/ruby/2.1.0/net/http.rb:863:indo_start' /usr/lib/ruby/2.1.0/net/http.rb:852:in start' /usr/lib/ruby/2.1.0/net/http.rb:583:instart' /usr/lib/ruby/gems/2.1.0/gems/retries-0.0.5/lib/retries.rb:46:in call' /usr/lib/ruby/gems/2.1.0/gems/retries-0.0.5/lib/retries.rb:46:in with_retries' /usr/lib/ruby/gems/2.1.0/gems/resque-1.26.0/lib/resque/job.rb:177:in block (3 levels) in perform' /usr/lib/ruby/gems/2.1.0/gems/newrelic_rpm-3.16.2.321/lib/new_relic/agent/instrumentation/resque.rb:41:in block in around_perform_with_monitoring' /usr/lib/ruby/gems/2.1.0/gems/newrelic_rpm-3.16.2.321/lib/new_relic/agent/instrumentation/controller_instrumentation.rb:363:in `perform_action_with_newrelic_trace'

/usr/lib/ruby/gems/2.1.0/gems/newrelic_rpm-3.16.2.321/lib/new_relic/agent/instrumentation/resque.rb:33:in around_perform_with_monitoring' /usr/lib/ruby/gems/2.1.0/gems/resque-1.26.0/lib/resque/job.rb:176:in block (2 levels) in perform' /usr/lib/ruby/gems/2.1.0/gems/resque-1.26.0/lib/resque/job.rb:172:in call' /usr/lib/ruby/gems/2.1.0/gems/resque-1.26.0/lib/resque/job.rb:172:in block (3 levels) in perform' ../app/jobs/resque_hooks.rb:15:in around_perform_job_duration' /usr/lib/ruby/gems/2.1.0/gems/resque-1.26.0/lib/resque/job.rb:172:in block (2 levels) in perform' /usr/lib/ruby/gems/2.1.0/gems/resque-1.26.0/lib/resque/job.rb:184:in call' /usr/lib/ruby/gems/2.1.0/gems/resque-1.26.0/lib/resque/job.rb:184:in perform' /usr/lib/ruby/gems/2.1.0/gems/resque-1.26.0/lib/resque/worker.rb:290:in perform' /usr/lib/ruby/gems/2.1.0/gems/resque-1.26.0/lib/resque/worker.rb:229:in block in work' /usr/lib/ruby/gems/2.1.0/gems/resque-1.26.0/lib/resque/worker.rb:206:in loop' /usr/lib/ruby/gems/2.1.0/gems/resque-1.26.0/lib/resque/worker.rb:206:in work' /usr/lib/ruby/gems/2.1.0/gems/resque-pool-0.6.0/lib/resque/pool.rb:396:in block in spawn_worker!' /usr/lib/ruby/gems/2.1.0/gems/resque-pool-0.6.0/lib/resque/pool.rb:389:in fork' /usr/lib/ruby/gems/2.1.0/gems/resque-pool-0.6.0/lib/resque/pool.rb:389:in spawn_worker!' /usr/lib/ruby/gems/2.1.0/gems/resque-pool-0.6.0/lib/resque/pool.rb:367:in block in spawn_missing_workers_for' /usr/lib/ruby/gems/2.1.0/gems/resque-pool-0.6.0/lib/resque/pool.rb:366:in times' /usr/lib/ruby/gems/2.1.0/gems/resque-pool-0.6.0/lib/resque/pool.rb:366:in spawn_missing_workers_for' /usr/lib/ruby/gems/2.1.0/gems/resque-pool-0.6.0/lib/resque/pool.rb:352:in block in maintain_worker_count' /usr/lib/ruby/gems/2.1.0/gems/resque-pool-0.6.0/lib/resque/pool.rb:350:in each' /usr/lib/ruby/gems/2.1.0/gems/resque-pool-0.6.0/lib/resque/pool.rb:350:in maintain_worker_count' /usr/lib/ruby/gems/2.1.0/gems/resque-pool-0.6.0/lib/resque/pool.rb:263:in start' /usr/lib/ruby/gems/2.1.0/gems/resque-pool-0.6.0/lib/resque/pool.rb:89:in run' /usr/lib/ruby/gems/2.1.0/gems/resque-pool-0.6.0/lib/resque/pool/tasks.rb:17:in block (2 levels) in ' /usr/lib/ruby/gems/2.1.0/gems/rake-11.2.2/lib/rake/task.rb:248:in call' /usr/lib/ruby/gems/2.1.0/gems/rake-11.2.2/lib/rake/task.rb:248:in block in execute' /usr/lib/ruby/gems/2.1.0/gems/rake-11.2.2/lib/rake/task.rb:243:in each' /usr/lib/ruby/gems/2.1.0/gems/rake-11.2.2/lib/rake/task.rb:243:in execute' /usr/lib/ruby/gems/2.1.0/gems/airbrake-5.5.0/lib/airbrake/rake/task_ext.rb:19:in execute' /usr/lib/ruby/gems/2.1.0/gems/rake-11.2.2/lib/rake/task.rb:187:in block in invoke_with_call_chain' /usr/lib/ruby/2.1.0/monitor.rb:211:in mon_synchronize' /usr/lib/ruby/gems/2.1.0/gems/rake-11.2.2/lib/rake/task.rb:180:in invoke_with_call_chain

samedi 14 octobre 2017

Using elasticsearch-extensions gem in Rails test

I'm using Elasticsearch in a Rails application and would like to be able to test the Elasticsearch code in automated tests. I've found the elasticsearch-extensions gem which allows you to spin up an Elasticsearch test cluster fairly easily. I cannot seem to actually get this running in a test though. I run the code:

Elasticsearch::Extensions::Test::Cluster.start(port: 9250, nodes: 1, timeout: 120)
client = Elasticsearch::Client.new url: 'http://localhost:9250'
client.index index: 'index', type: 'type', id: 1, body: { name: 'test' }, refresh: true

If I ran this via the Rails console or the Rails runner, I can query the Elasticsearch cluster and see that a cluster was made and an index was created. However, if I do this in a test, like so:

require 'elasticsearch/extensions/test/cluster'

class ElasticsearchTest < ActiveSupport::TestCase
  context 'running an elasticsearch cluster' do
    should 'create an index when adding a document' do
      Elasticsearch::Extensions::Test::Cluster.start(port: 9250, nodes: 1, timeout: 120)
      client = Elasticsearch::Client.new url: 'http://localhost:9250'
      client.index index: 'index', type: 'type', id: 1, body: { name: 'test' }, refresh: true
    end
  end
end

it doesn't work, and I cannot figure out why. Any ideas?

Web application could not be started redmine3.4

Sir now i am getting different error Web application could not be started

Web application could not be started There was an error while trying to write to Gemfile.lock. It is likely that you need to allow write permissions for the file at path: /usr/share/redmine/Gemfile.lock (Bundler::InstallError) /usr/lib/ruby/vendor_ruby/bundler/definition.rb:235:in rescue in lock' /usr/lib/ruby/vendor_ruby/bundler/definition.rb:220:inlock’ /usr/lib/ruby/vendor_ruby/bundler/environment.rb:34:in lock' /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:43:insetup’ /usr/lib/ruby/vendor_ruby/bundler.rb:120:in setup' /usr/lib/ruby/vendor_ruby/bundler/setup.rb:17:in’ /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in require' /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:inrequire’ /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:245:in block in run_load_path_setup_code' /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:348:inrunning_bundler’ /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:243:in run_load_path_setup_code' /usr/share/passenger/helper-scripts/rack-preloader.rb:100:inpreload_app’ /usr/share/passenger/helper-scripts/rack-preloader.rb:158:in ' /usr/share/passenger/helper-scripts/rack-preloader.rb:29:inmodule:PhusionPassenger’ /usr/share/passenger/helper-scripts/rack-preloader.rb:28:in `’

rails edit_model_name_url(@model_name) does not take me to edit page

i want to redirect to edit page on dropdown change event from new page. if data is present in database for selected week then display that data in edit page. for this i use ajax method . this is working perfectly

 $('select#weeknumber').on('change', function(event) {
  var selected_id= $(this).val();
  $.ajax({
    type:'post',
    url:'/clients/changeweek/',
     data:{ week: selected_id}       

});      

});

Inside my controller i have a changeweek method from which i want to redirect to edit page with specific id.For this i used redirect_to which creates the link which i want but the edit page did not load it still remains on new.html.erb

def changeweek 
@weekcheck = Client.where('weeknumber = ?',params[:week])

   if @weekcheck.nil?
    @clientdata = Client.new(params[:weeknumber] => params[:week])
    redirect_to new_client_path(@client)
    else
    @client = Client.find_by('weeknumber = ?',params[:week])
    redirect_to edit_client_url(@client)
    end

end

Please help me

vendredi 13 octobre 2017

Disable GET for Devise routes, Rails 5

I have Rails 5 with Devise with Ajax login/registration and I want to remove GET requests for these two actions. The default sign_in/sign_up routes are changed. This is my routes.rb:

devise_for :users, :path => '', :path_names => { :sign_in => "login", 
                       :sign_out => "logout", :sign_up => "registration" }, 
                       :controllers => {:sessions => 'sessions', 
                                        :registrations => 'registrations'

resque scheduler not enqueue jobs

Schedules exist to be executed at certain times as defined in the schedule, but the tasks are not executed.

There is an option in the schedule to manually start that specific scheduled task and that will execute and perform the tasks. This shows that the task can be performed, it is just not starting automatically.

cannot load such file -- mysql2/2.4/mysql2 - Ruby 2.4

I have Ruby 2.4 and trying to install mysql2 . I follow the instructions from internet:

  1. gem uninstall mysql2 - if needed;
  2. download mysql connector;
  3. gem install mysql2 --platform=ruby -- '--with-mysql-lib="C:\conn\lib" --with-mysql-include="C:\conn\include"' and see message - 1 gem is installed;
  4. copy file libmysql.lib to rubyFolder/bin

If run rails s I see this message:

Could not find mysql2-0.4.8-x64-mingw32 in any of the sources Run bundle install to install missing gems.

and I do it - bundle, but after that, if I run again rails s I see same error:

C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:292:in `require': cannot load such file -- mysql2/2.4/mysql2 (LoadError)

jeudi 12 octobre 2017

jpg Image brighter on Chrome than other browsers

These are screenshots from chrome of a jpg image I added to my site. The css and html are the same and everything and I've been adding images the same way for years and have not had this problem. Why is this chrome image brighter than the safari image? And How do I fix it???

This is the chrome image

enter image description here

This is the safari image

enter image description here

Slow loading Rails 5.1.4 with Ruby 2.3.3-p222

I have standard view with 1 database query (MySQL). I am using Devise and method for checking is it user logged in layouts/application.html.erb:

<% unless user_signed_in? %>
    <%= render 'partials/login_modal' %>
    <%= render 'partials/registration_modal' %>
<% end %>

Layout is with 4 partials included (_header.html.erb and _footer.html.erb, too). All generated HTML (from html tag to html) is around 320 lines.

In production I set : config.assets.raise_runtime_errors = false.

The site loads really slow, but only the first time, right after starting server and it doesn't matter which page loads, it is same for all .

In production:

  • FontAwesome loads for 20ms;
  • the CSS file for 8ms,
  • JS file - 14 ms and three images around 10-20ms each.

The page which is 11Kb loads for more than 9 seconds.

In development, same page, I have different requests for assets (9 CSS/JS/img files, each between 20 -50ms for loading) and same page (11.4Kb) loads for more than 11 seconds.

I read in the console when it s development mode:

Started GET "/contacts" for 127.0.0.1 at 2017-10-12 23:33:48 +0300

(1.0ms) SET @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'), @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483

(1.0ms) SELECT schema_migrations.version FROM schema_migrations ORDER BY schema_migrations.version ASC

Processing by ContactsController#index as HTML

Rendering index.html.erb within layouts/application

Rendered index.html.erb within layouts/application (1.0ms)

Rendered partials/_header.html.erb (1.0ms)

Rendered partials/_footer.html.erb (0.0ms)

Rendered partials/_login_modal.html.erb (1.0ms)

Rendered partials/_registration_modal.html.erb (0.0ms)

I am using Windows 10, but is same on Ubuntu. It is same and if I upload site to Heroku and only first time when browser loads the site.

Need help interpreting this rails asset file extension: foobar.js.jst.jsthtml.haml

I've inherited a Ruby on Rails & AngularJS web app. Some of the static assets have the file extension.js.jst.jsthtml.haml, and I'm trying to unpack what each part of the extension means:

Can someone help me flesh this out, especially what the .jsthtml extension is for?

NoMethodError in ParticipantsController#new

Why does the error occur?

There hasen't been an adquate/similar solution for my problem. I just could find some tips and tricks here but now I am stuck.

We have a course management system. You can add new coures, participants and persons among other things. I had to change the database. Now there is a persons table, too. Earlier all informations about persons respectively participants where just saved in the participants table. Now when a new participant is added the persons table is involved. We want to add a new participant of a course. I adjusted the new action in the participants controller and I was hoping passing all data like in the old way. The old way was working to add a new participant.

Earlier the way was: course > new participant form

Now it is: course > search for a person to use it in the form > new participant form

I think (better ways accepted) I just adjust the old code?! Below is my try.

The Error

NoMethodError in ParticipantsController#new undefined method `participants' for []:Array

occurs.

Here are the old classes:

Model Course

class Course < ActiveRecord::Base
  has_many :participants

Model Participant

class Participant < ActiveRecord::Base
  belongs_to :course
  belongs_to :organization
  belongs_to :function

ParticipantsController

class ParticipantsController < ApplicationController

....
 def new
    @course = Course.find(params[:course_id])
    @participant = @course.participants.build

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @participant }
    end
  end

 def create
    @course = Course.find(params[:course_id])
    @participant = @course.participants.new(params[:participant])
    @course.updated_by = current_user.cn
    @course.send(:create_version)
    @course.tag_version(t(:participant_added))
    @course.save!

    respond_to do |format|
      if @participant.save
        format.html { redirect_to course_path(@participant.course), notice: 'Participant was successfully created.' }
        format.json { render json: @participant, status: :created, location: @participant }
      else
        format.html { render action: "new" }
        format.json { render json: @participant.errors, status:     :unprocessable_entity }
      end
    end
  end

When you look below at the course view snippet there is the old and new path to the form. Note that the person search is in between the course and the new participant form now.

**old**    <%= link_to t(:add), new_course_participant_path(@course) %>

**new**    <%= link_to t(:add), course_persons_path(@course, @person)%>

Here are the new classes

class Participant < ActiveRecord::Base
  belongs_to :course
  belongs_to :function
  belongs_to :person

class Person < ActiveRecord::Base
  has_many :participants
  has_many :courses, through:  :participants

Here are my adjustments in the ParticipantsController. My thoughts are maybe naive because I am still learning ruby on rails.

class ParticipantsController < ApplicationController
    def new
       @person = Person.find(params[:person_id])
       @participant = Participant.find_by_person_id(params[:person_id])
       @course= Course.find(:all, :conditions => {:id => @participant})
       @participant = @course.participants.build

 def create 
    @course= Course.find(params[:course_id])
    @participant = @course.participants.new(params[:participant])
    @course.updated_by = current_user.cn
    @course.send(:create_version)
    @course.tag_version(t(:participant_added))
    @course.save!

    respond_to do |format|
      if @participant.save
        format.html { redirect_to course_path(@participant.course), notice:     'Participant was successfully created.' }
        format.json { render json: @participant, status: :created, location: @participant }

      else
        format.html { render action: "new" }
        format.json { render json: @participant.errors, status: :unprocessable_entity }
      end
    end
  end

Thanks in advance

Specify the extraction directory of Ruby Application via OCRA (One Click Ruby Application)

I'm using OCRA to create a portable Ruby on Rails application. Unfortunately, I encounter an error that goes like this:

missing helper file helpers/application_helper.rb helper.rb

From what I researched, this error has something to do with the case sensitivity issue on Ruby 2.2, where using C:\User\Sites would cause an error.

With this I converted it to a higher version ruby (2.3) and still the error exists. Upon inspection, aside from the case issue, I've noticed that some of the characters were changed as well (dot to dash, so ocr.xxx becomes ocr-xxx).

Now my question is, is there a way to specify to which directory should OCRA be extracting the code? I ws thinking of placing it somewhere else other than the TEMP directory that seems to be an issue for me.

mercredi 11 octobre 2017

Get hash of id => property in Rails

I have an ActiveRecord model like this:

class Person < ActiveRecord::Base
  attr_accessible :name
end

and need to get a hash mapping persons ids to their names. Now, the obvious way would be

Person.all.collect { |p| [p.id, p.name] }.to_h

However, I don't need to instantiate every Person, I just need the hash. In Rails 4, I can .pluck(:id, :name) instead of collect, however in 3.x, pluck takes only one argument. However I found this workaround to get what I want without loading the models:

Person.all.group(:id).minimum(:name)

Question: will I burn in hell? Also, is there a more elegant way to do this, and are there any drawbacks of this hacky approach that I may not be aware of? Thanks!

Custom validator on associated model make other Rspec model tests break

I have 2 models sharing a simple belong_to/has_many relation: Room belongs to Building

I created a custom validator called total_number_rooms_limited_to_15 that ensures I can't create more than 15 rooms for a given Building.

class Room < ActiveRecord::Base

    # -- Relationships --------------------------------------------------------
  belongs_to :admin_user,     :foreign_key => 'admin_user_id'
  belongs_to :building,        :foreign_key => 'building_id'

  # -- Validations ----------------------------------------------------------              

  validates :room_filename,
              presence: true             

  # associated models primary key validates 
  validates :admin_user_id,
     presence: true
  validates :building_id,
     presence: true  

  validate :total_number_rooms_limited_to_15

  private

    def total_number_rooms_limited_to_15
      errors[:base] <<  "There can't be more than 15 rooms. There are already 15 .
                        <br/>Please remove another one or drop trying adding this one.".html_safe unless ( self.building.rooms.count < 15 )
    end

But the problem is that after creating this new validator, all my "usual" basic tests fail.

require 'spec_helper'

RSpec.describe Room, type: :model do

  before(:each) do
    @attr = {
      room_filename:                               "xyz" 
    }
  end  

  # -- Models Tests --------------------------------------------------------
  describe "tests on ST's models validations for room_filename" do
    it { is_expected.to validate_presence_of(:room_filename) }    
    it { is_expected.not_to allow_value(" ").for(:room_filename) }    
  end

All give me the following error message:

1) Room tests on ST's models validations for room_filename should validate that :room_filename cannot be empty/falsy
     Failure/Error:
       errors[:base] <<  "There can't be more than 15 rooms. There are already 15 .
                         <br/>Please remove another one or drop trying adding this one.".html_safe unless ( self.rooms.count < 15 )

     NoMethodError:
       undefined method `rooms' for nil:NilClass

I tried adding inside @attr the attribute a associated "virtual" building but it not work out;, getting the same error message:

before(:each) do
    @attr = {
      room_filename:                               "xyz",
      building_id:                                 1
    }

mardi 10 octobre 2017

rails twitter gem list retrieve full tweet when truncated

I am displaying the tweets from a public list but when a tweet has an image it is not displaying the image nor the link of the image but ... and sometimes even the text of the tweet is truncated with ....
How can I make the full tweet text display even if the image is not?
I need the full text for each tweet in the list.

lundi 9 octobre 2017

import records using the gem roo

I am trying to import records to the database using the gem roo using excel files, it works pretty well making use of this tutorial, I am importing nested records belonging to the relation "has_one" when importing again the excel me updates the data, but how can I update the data of those nested resources that are of "has_many"? if every time I import the file with the same data again it re-creates the record, this is my model:

class Cliente < ActiveRecord::Base

  has_many :reldaycli, class_name: "Reldayc", foreign_key: "CodCli"
  accepts_nested_attributes_for :reldaycli, reject_if: proc{|attributes| attributes['RutaId'].blank?}


    def self.import(file,empresa)#importar
      @errors = []
      spreadsheet = open_spreadsheet(file)
      header = spreadsheet.row(1)
      (2..spreadsheet.last_row).each do |i|
        row = Hash[[header, spreadsheet.row(i)].transpose]
        cliente = find_by_IdCli(row["Clave"]) || new
        cliente.attributes = {IdCli: row["Clave"], Nombre: row["Encargado"], NombreCorto: row["Nombre Comercial"], Direccion: row["Calle y N°"], CP: row["C.P"], Colonia: row["Colonia"], Latitud: row["Latitud"], Longitud: row["Longitud"], Referencia: row["Referencia"], Status: row["Activo"], Telefono: row["Teléfono"], Tel2: row["Tel. Celular"], Email: row["Email"], Horario: row["Horario"], Credito: row["Credito"], LimiteCredito: row["Limite Credito"], DiasCreedito: row["Días Credito"], Saldo: row["Saldo inicial"], VisitaObligada: row["Visita Obligada"], FirmaObligada: row["Firma Obligada"], IdEmpresa: empresa}


        cliente.reldaycli_attributes = [{RutaId: row["IdRuta"], idVendedor: row["IdVendedor"], Lunes: row["Lunes"], Martes: row["Martes"], Miercoles: row["Miércoles"], Jueves: row["Jueves"], Viernes: row["Viernes"], Sabado: row["Sábado"], Domingo: row["Domingo"], IdEmpresa: empresa}]



        if cliente.save
          # stuff to do on successful save
         else
           cliente.errors.full_messages.each do |message|
             @errors << "Error fila #{i}, columna #{message}"
           end
         end


      end
      @errors #  <- need to return the @errors array
    end

end

vendredi 6 octobre 2017

How to Solve Dropbox {“error”: “v1_retired”} for the Dropbox API in ruby on rails

def passport_upload doc
    # begin

        app_key = ENV['WINGBE_DROPBOX_APP_KEY_DEVELOPMENT'] 
        app_secret = ENV['WINGBE_DROPBOX_APP_SECRET_DEVELOPMENT']
        p "=========#{app_key}===#{app_secret}========="    
        flow = DropboxOAuth2FlowNoRedirect.new(app_key, app_secret)
        authorize_url = flow.start()
        client = DropboxClient.new(ENV['WINGBE_DROPBOX_ACCESS_TOKEN_DEVELOPMENT'])          
        file = open(params[:doc])
        file_name = params[:doc].original_filename 
        response = client.put_file(file_name, file)
        # response = client.put_file('file_name', open('file'))
        client.shares(response['path'])
    # rescue
    # end   
end

Useing dropbox api through upload the any file on dropbox got error Dropbox {“error”: “v1_retired”} How to resolve it.

Ruby on Rails - You are not authorized to access this page

The Error is You are not authorized to access this page. in former collagues code.

When a user clicked Click me (table below, in person index page) the user should be led to the new page (participant) in order to create a new participant. But if it's clicked, the error rises. Btw the index page for participants is accessible?! I am too new to ROR to code in the ability model (if even necessary). I would first like to have a clue what's going on with the code and why I cannot access the new page to create a new participant.

cancan and devise is used. I guess it has something to to with those but I am too confused right now and I don't know where to start =/.

User Story

If you want to create a new participant of a course you can use a search function which I coded. With this you can search for persons that are already in the system (this works so far). When you've found the desired person, you can click on Click meand you should be led to a page where you can use the persons information to create a new participant of a course.

+-------+---------+---------+----------+
| Title | Prename | Surname |   Use    |
+-------+---------+---------+----------+
| Dr.   | John    | Doe     | Click me |
+-------+---------+---------+----------+

Here is the ParticipantsController

class ParticipantsController < ApplicationController

before_filter :authenticate_user!, :except => [:index, :show]
before_filter :my_authenticate_user, :only => [:show]
load_and_authorize_resource :course
load_and_authorize_resource :participant, :through => :course, :only => [:new, :create, :destroy]
 def index

   @participants = Participant.all

   respond_to do |format|
     format.html # show.html.erb
     format.json { render json: @participant }
   end
 end
 def new
   @course = Course.find(params[:course_id])
   @participant = @course.participants.build
  respond_to do |format|
     format.html # new.html.erb
     format.json { render json: @participant }
   end
 end

 def edit
   @participant = Participant.find(params[:id])
   authorize! :edit, @participant 
 end
def create
   @course = Course.find(params[:course_id])
   @participant = @course.participants.new(params[:participant])
   @course.updated_by = current_user.cn
   @course.send(:create_version)
   @course.tag_version(t(:participant_added))
   @course.save!
   respond_to do |format|
     if @participant.save
       format.html { redirect_to course_path(@participant.course), notice: 'Participant was successfully created.' }
       format.json { render json: @participant, status: :created, location: @participant }

     else
       format.html { render action: "new" }
       format.json { render json: @participant.errors, status: :unprocessable_entity }
     end
   end
 end
 def update
  @participant = Participant.find(params[:id])
   authorize! :update, @participant

   respond_to do |format|
     if @participant.update_attributes(params[:participant])
       format.html { redirect_to @participant, notice: 'Participant was successfully updated.' }
       format.json { head :no_content }
     else
       format.html { render action: "edit" }
       format.json { render json: @participant.errors, status: :unprocessable_entity }
     end
   end
 end

 def destroy
   @course = Course.find(params[:course_id])
   @participant = @course.participants.find(params[:id])
   @participant.destroy
   redirect_to course_path(@course)
 end
private

 def my_authenticate_user
   myreturn = false
   @public_function_ids = Function.select("id").where(:english => ["Sponsor","Principal Investigator","Responsible contact"])
   @participant = Participant.find(params[:id])
   @public_function_ids.each do |p|
     if p.id == @participant.function_id
       myreturn = true
     end
   end
   if myreturn == false
     authenticate_user!
   else
     return myreturn
   end
 end
end

Here is the PersonsController

class PersonsController < ApplicationController

before_filter :authenticate_user!, :except => [:new, :index, :show]
 load_and_authorize_resource :course
 load_and_authorize_resource :person, :through => :participant, :only => [:create, :destroy]
 helper_method :sort_column, :sort_direction

 autocomplete :person, :prename, :display_value => :display_autocomplete, :extra_data => [:title,    :prename, :surname]
  autocomplete :person, :surname, :display_value => :display_autocomplete, :extra_data => [:title, :prename, :surname]
  autocomplete :organization, :description, :full => true, :limit => Rails.configuration.autocomplete_limit
  def index
    unless params[:search_me]
      @search_me = ''
    else
      @search_me = params[:search_me]
    end

    if params[:search_me]
     @persons = Person.search_me(params[:search_me]).order(sort_column +' ' + sort_direction).paginate(:per_page => 5, :page => params[:page])
    else
    @persons = Person.select('persons.*, count(participants.person_id) 
    AS participant_count').joins(:participants).group('participants.person_id').order('participant_count desc').limit(3)
    end

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @persons }
    end
  end

  def show
    @person = Person.find(params[:id])
    authorize! :show, @person

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @person }
    end
  end

def new
    @person = Person.new
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @person}
    end
  end

def edit

    @person = Person.find(params[:id])
    authorize! :edit, @person # 
  end

  def create
    @person = Person.new(params[:person])
    @person.courses << @course
    respond_to do |format|
      if @person.save
        format.html { redirect_to @person, notice: 'Person was successfully created.' }
        format.json { render json: @person, status: :created, location: @person }
      else
        format.html { render action: "new" }
        format.json { render json: @person.errors, status: :unprocessable_entity }
      end
    end
  end

def update
   @person = Person.find(params[:id])
    authorize! :update, @person
    respond_to do |format|
      if @person.update_attributes(params[:person])
        format.html { redirect_to @person, notice: 'Person was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @person.errors, status: :unprocessable_entity }
      end
    end
  end

def destroy
    @person = Person.find(params[:id])
    @person.destroy
    respond_to do |format|
      format.html { redirect_to person_url }
      format.json { head :no_content }
    end
  end



  private

  def sort_column
    Person.column_names.include?(params[:sort]) ? params[:sort] : "prename"
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
  end
  def my_authenticate_user

   …
  end
end

Here is the Participant model

class Participant < ActiveRecord::Base

  belongs_to :trial
  belongs_to :function
  belongs_to :person

  attr_accessible :trial_id, :function_id, :person_id, :person_prename

Here is the Person model

class Person < ActiveRecord::Base
  belongs_to :organization
  attr_accessible     :organization_id,:title,:prename,:surname,:street,

:street_number,:zip_code,:city,:phone,:fax,:email,:organization_description has_many :participants has_many :courses, through: :participants

Here is the app/views/persons/_index_tail.html.erb

<fieldset>
<legend class="bold"><% if params[:search_me]%><%="Results%><%else%><%="Top 3 used participants"%><%end%></legend>

<table class="person center">
<tr>
  <th><%= t(:title) %></th>
  <th><%= t(:prename)%></th>
  <th><%= t(:surname) %></th>
  <th><%= t(:street) %></th>
  <th><%= t(:city) %></th>
  <th>Verwenden</th>

 </tr>
<%# @personcount = 0 %>
<% @persons.each do |person| %>
<tr>
  <td><%=person.title %></td>
  <td><%=person.prename %></td>
  <td><%=person.surname %></td>
  <td><%=person.street %></td>
  <td><%=person.city %></td>
  <%if user_signed_in?%>
  <td><%= link_to image_tag("user_silhouette.png", 
  { :title => t(:show) }), new_participant_path(@participant) %></td>
  <%end%>
  </tr>
  <% end %>
  </table>
</fieldset>

removing duplicate entry for csv import in ruby

while importing csv row i need to check wether this is duplicate entry or new entry. my csv looks like this,

         company,location,region,service,price,duration,disabled
         Google,Berlin,EU,Design with HTML/CSS,120,30,false
         Google,San Francisco,US,Design with HTML/CSS,120,30,false
         Google,San Francisco,US,Restful API design,1500,120,false
         Apple,London,EU,Design with HTML/CSS,120,30,false
         Google,Berlin,EU,Design with HTML/CSS,120,30,false
         Apple,Berlin,EU,Restful API design,1500,120,false

Also the row value should be imported in different table whose association is like this

A Company:

  • can have multiple regions: US, EU and each region multiple branches, i.e. London, Berlin. Define a hierarchy to represent this logic.
  • has many Services. If there are more branches, they will all share the same services
  • can be disabled

A Service:

  • has a duration
  • has a price
  • can be disabled
  • if the company is disabled, all services are disabled.

for which i have implemented association like this

       class Company < ApplicationRecord
         has_many :regions
         has_many :services
         has_many :locations, through: :regions
       end

        class Region < ApplicationRecord
         belongs_to :company
           has_many :locations
        end

        class Location < ApplicationRecord
          belongs_to :region
          belongs_to :company
        end

        class Service < ApplicationRecord
          belongs_to :company
         end

How will I import this?

jeudi 5 octobre 2017

uninitialized constant ruby model

I have 3 classes:
1. Article

class Article < ActiveRecord::Base
has_many :categories_articles
has_many :subcategories_articles
has_many :categories, :through => :categories_articles
has_many :subcategories, :through => :subcategories_articles
end

2.Category

class Category < ActiveRecord::Base
has_many :articles
has_many :categories_articles
has_many :categories_subcategories
has_many :subcategories, :through => :categories_subcategories
has_many :articles, :through => :categories_articles
end

3.The third class is the union of the first two, category_article

class CategoryArticle < ActiveRecord::Base
belongs_to :category
belongs_to :article
end

so, when i called in the view

<% f.collection_select(:category_ids, Category.all, :id, :name, {include_blank:"selects"},{class:'form-control select2 multi', :required=>true, multiple: true}) %>

i get this error

uninitialized constant Article::CategoriesArticle

The same goes for the class Subcategory and subcategory_article

has_many to has_many, add attribute to the join table

Hi I have a primary model, recipes with a has_many association with ingredients, which also has_many recipes, my join table is recipes_ingredients, the join table has the columns recipe_id, ingredient_id, and quantity. The quantity is just a string for how many times that ingredient will be used in that recipe.

I have a form that creates the recipe and saves it in the database at the same time it creates and saves any ingredients that are given in the form with a nested attribute... I cannot for the life of me figure out how to add the quantity for this join-table using this same form. I would appreciate any help you can afford me... thank you so much in advance.

**models
class Recipe < ApplicationRecord
belongs_to :user
has_many :recipe_ingredients
has_many :ingredients, through: :recipe_ingredients
validates :name, :content, :cook_time, presence: true

  def ingredients_attributes=(ingredients_hash)
    ingredients_hash.each do |i, ingredients_attributes|
        if ingredients_attributes[:name].present?
            ingredient = Ingredient.find_or_create_by(name: 
         ingredients_attributes[:name].capitalize!)
            if !self.ingredients.include?(ingredient)
                self.recipe_ingredients.build(:ingredient => 
        ingredient)
            end
        end
    end
end


class Ingredient < ApplicationRecord
has_many :recipe_ingredients
has_many :recipe, through: :recipe_ingredients
validates :name, presence: true

class RecipeIngredient < ApplicationRecord
belongs_to :ingredient 
belongs_to :recipe
end

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

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

     <div class="container">
     <div class="row">
     <div class="col-sm-6">
      <h3 class="text-center">Recipe</h3>
      <div class="fields">
        <%= form.label :name %><br>
        <%= form.text_field :name, :placeholder => "Name" %><br>
        <%= form.label "Instructions"  %><br>
        <%= form.text_area :content, :placeholder => "Recipe 
        Instructions" %><br>
        <%= form.label :cook_time %><br>
        <%= form.text_field :cook_time, :placeholder => "(ex,. 45 
        mins)" %><br>
        <%= form.hidden_field :user_id, value: params[:user_id] %>
      </div>
      </div>

       <div class="col-sm-6">
        <h3 class="text-center">Ingredients</h3>
        <div class="row">
          <div class="col-sm-6 checkbox">
                <%= form.collection_check_boxes(:ingredient_ids, 
            Ingredient.all, :id, :name) %> 
            </div>
            <div class="col-sm-6">
                <%= form.fields_for :ingredients do 
            |ingredient_builder| %>
                    <%= ingredient_builder.text_field :name %><br>
                <% end %>
              </div>
            </div>
        </div>
       </div>

        <div class="row justify-content-center submit-row">
         <div class="fields text-center">
          <%= form.submit %>
       </div>
      </div>


     </div>