Tuesday, August 30, 2016

using data-rel tag, link to a div in dinamically process with Ruby on Rails | Fixed issues

using data-rel tag, link to a div in dinamically process with Ruby on Rails | Fixed issues


using data-rel tag, link to a div in dinamically process with Ruby on Rails

Posted: 30 Aug 2016 08:38 AM PDT

I want to do a Facybox, using this method in the tutorial : http://sohtanaka.developpez.com/tutoriels/javascript/creez-fenetre-modale-avec-css-et-jquery/fichiers/

The problem is that the "data-rel" tag seems to don't work in dinamically circumstances. here is my code:

  <div class="row prod">      <% @type1.each do |product| %>        <div class="product-tile">          <div class="entry col-xs-2 col-xs-offset-0 col-sm-4 col-sm-offset-0 col-md-4 col-md-offset-0 col col-lg-4 col-lg-offset-0 col">            <h3><%= product.title %></h3>            <div class="product_img img-responsive">              <%= image_tag(product.image_url, :class => 'the_img') %>              <a href="#" data-width="1000" data-rel="popup1" class="poplight discover">Discover</a>               <h3><%=product.title%></h3>                <div id="popup1" class="popup_block">  	               <h3><%=product.title%></h3>                   <%= image_tag(product.image_url, :class => 'the_img') %>  	                <p>Soh Tanaka est traduit sur developpez.com.</p>                </div>            </div>            <div class="product_description">              <%= sanitize(product.description)%>              <div class="price_line">                <span class="price"><%=number_to_currency(product.price)%></span>              </div>            </div>          </div>        </div>      <%end%>    </div>

The <%=product.title%> and <%product.image_url%> gives me always the same result : the first occurrence from my database. how could I fix it? Thanks!

Rails file_filed doesn't pass params

Posted: 30 Aug 2016 08:25 AM PDT

I have trouble with my image update

My form

  = form_for @user, :html => {class: "form form_profile"} do |user|      = user.file_field :avatar   .... other fields    end   

and controller update and user_avatar_params action

def update   respond_to do |format|         # binding.pry        if params[:user][:avatar]            if current_user.update(user_avatar_params)            flash[:notice] = 'Updated            format.html { render action: 'edit' }            format.js { render 'success_edit', layout: false }   ....  end           def user_avatar_params      params.require(:user).permit(:avatar)   end  

my params from console

{"utf8"=>"✓", "_method"=>"patch", "user"=>{"current_password"=>"", "password"=>""}, "action"=>"update", "controller"=>"users", "id"=>"2"}  

i use paperclip

What wrong with it?

Rails 4 API, how to create a URL from a JSON response?

Posted: 30 Aug 2016 08:42 AM PDT

I'm working on an API where I have a few routes setup, ie

http://localhost:3000/phone_number_lookup/1234567890

which can return a JSON response like so:

{  "AccountCode": "1234",  "AccountID": 13579,  "BalanceCurrent": "5000",  "Phone": "1234567890",  "Id": 123123,  "SerialNumber": "Y2K2000XY2016",  "MACADDRESS": "y2k2000xy2016",  "EQUIPMENTTYPE_Name": "Motorola DCX100 HD DVR",  "ADDRESS_Zip": "90210",  "ItemID": 12345,  "iVideoSystemID": 1000001  "id": null  }  

The next 'step' of the API consumption would be, 'given the initially returned response, use 4 of those parameters and pass them into a remote URL that will then do something.'

Like so:

http://myremoteURL.com/Service/Param1?=sSerialNumber&Param2=iVideoSystemID&Param3=sMAC&Param4=ItemID

It would be one thing to just set up a route that takes 4 parameters, but the route needs to be contingent on what the initial JSON response was.

What is the proper way to do this?

Why won't my Angular app send params to my Entangle rails controller?

Posted: 30 Aug 2016 08:16 AM PDT

In an effort to learn about realtime apps, I am trying to create a basic messageboard using Entangled.

I have an Angular app and a Rails backend with a Messages Controller that includes Entangled::Controller. This Rails controller successfully receives a request when a form is submitted from the Angular app - the form is submitted using Entangled. (On clicking submit, a function is triggered in an Angular controller which should create a new message in the backend and update all clients subscribed to that backend.)

I know the Angular function is being triggered on clicking submit, and I know the function receives the correct information from the form: console.log($scope.message) displays {socket: "ws://message-board-olliehm.c9users.io:8080/messages", username: "ggg", content: "gggggg"} where I submit "ggg" in the username field and "gggggg" in the content field.

The problem is that these fields are not arriving at the Rails controller. When I click submit, the correct action is triggered in the Rails controller, but the params don't contain the right information: p params in def create returns {"controller"=>"messages", "action"=>"create"}, with no "message" hash and no "username" or "content" keys.

I cannot work out what Entangled is doing with the username and content fields.

Redis is new to me so I'm not sure if the problem is there. I have Redis installed and the redis-server is running as required by Entangled. I have a redis initializer as below, which in the Rails console is successfully connecting and letting me put data in the database:

$redis = Redis.new(:host => $IP, :port => 6379)  

Here's my Angular controller:

var controllers = angular.module('controllers');    controllers.controller('MessageboardController', ['$scope','Message', function($scope,Message){      $scope.message = Message.new();      $scope.post = function() {      console.log($scope.message);      $scope.message.$save(function() {        $scope.$apply(function() {          $scope.message = Message.new();        });      });    };      Message.all(function(err, messages) {      $scope.$apply(function() {        $scope.messages = messages;      });    });    }]);  

Message here refers to this factory:

messageboard.factory('Message', function(Entangled){    return new Entangled('ws://message-board-olliehm.c9users.io:8080/messages');  });  

And here's my Angular view:

<h1>Messageboard</h1>    <section class='row' ng-if='messages'>    <ul>      <li ng-repeat='message in messages'>        {{messages.username}}        {{messages.content}}      </li>    </ul>  </section>    <section class='row'>    <form ng-submit="post()">      <div class='form-group'>        <label for='username'>Message as</label>        <input ng-model='message.username' name='username' type='text'>      </div>      <div class='form-group'>        <input ng-model='message.content' name='message' type='text' placeholder='Write your message here'>      </div>      <div class='form-group'>        <input type="submit">      </div>    </form>  </section>  

Advice would be hugely appreciated - this has caused prolonged frustration and I'm very keen to get stuck into creating something with realtime updates.

Rails Mailer does not pick up on the host

Posted: 30 Aug 2016 08:04 AM PDT

Site is in sub-directory /app

In development.rb:

config.action_mailer.default_url_options = { host: 'localhost:3000/app' }

Url generated in the mailer item_url(1):

localhost/item/1, it should be: localhost:3000/app/item/1

How to replace localhost with localhost:3000/app?

Rails: 4.1.15

How do I save a carrierwave original image as a png but all versions as jpg?

Posted: 30 Aug 2016 07:57 AM PDT

The original image that is uploaded is a png file with transparency. Upon upload, I would like to create multiple versions, all jpg filing in the transparency with white background, but keep the original as a png.

The file names are UUID'd for CDN which will be enabled once I figure this out. I have used the recommended method for UUID per carrierwave docs and attempted to modify for my specific case.

The uploader included below successfully uploads to s3. The hashed files appear to be correctly named -- they contain a hash as well as the correct extension.

  • 123-456-789.png
  • web_123-456-789.jpg

Error 1

Images are stored in the db incorrectly. If I enter the rails console and attempt to output the image url the extension is '.png' even though the uploaded file in s3 is a '.jpg'

product.primary_image.recreate_versions!  product.save!  product.primary_image.web.url => https://../web_123-456-789.png  

Error 2

Looking at the file web_123-456-789.jpg in s3 and clicking 'properties' shows the content-type is 'image/png' I am using Carrierwave 0.11.2 so content-type is supposed to be set for me was my understanding.

Uploader file

# encoding: utf-8  class PrimaryUploader < CarrierWave::Uploader::Base    include CarrierWave::MiniMagick      storage :fog      def store_dir      "#{model.class.to_s.underscore.pluralize}/#{model.product_number}/claw"    end      version :web do      process resize_and_pad: [400, 400, '#FFFFFF', 'Center']      process convert: 'jpg'    end      ... other similar versions ...      def filename      if version_name != nil        ext = "jpg"      else        ext = "png"      end      "#{secure_token}.#{ext}" if original_filename.present?    end      protected      def secure_token      var = :"@#{mounted_as}_secure_token"      model.instance_variable_get(var) || model.instance_variable_set(var, SecureRandom.uuid)    end  end  

Rails5 - Ordering with Class method and params

Posted: 30 Aug 2016 07:38 AM PDT

In Rails, I want to order some tweets by number of likes desc using paramsand I am stuck..

I wrote a simple Class method in my model:

class Twit < ApplicationRecord    def self.most_liked   order(like: :desc)  end    end  

And here is my method in my controller:

class TwitsController < ApplicationController     def index    if params[:filter]     @twits = Twit.most_liked(params[:filter])    else     @twits = Twit.all    end   end    end  

If I only use @twits = Twit.most_liked, it works fine, but when I add my condition with params it fails.

Thank you !

Access the radio-button from rails form in javascript

Posted: 30 Aug 2016 07:33 AM PDT

I am building a rails app. I would like to access the radio_button value in Java Script(in document.getElementById). Below is the code snippet from the form.html.erb. Kindly let me know on how to access the same. I tried a lot of options. But nothing worked.

<div class="field">    <div class="container-fluid">      <div class="row">        <div class="col-md-6">          <div class="col-md-4">            <%= "Yet to start" %>            <%= radio_button("development_activity", "progress", "Yet to start", :checked => true) %>          </div>          <div class="col-md-4">            <%= "In Progress" %>            <%= radio_button("development_activity", "progress", "In Progress") %>          </div>          <div class="col-md-4">            <%= "Completed" %>            <%= radio_button("development_activity", "progress", "Completed") %>          </div>        </div>      </div>    </div>  </div>

Rails singleton client lost after a Rails crash

Posted: 30 Aug 2016 07:28 AM PDT

I have several third party APIs I need to connect to, so I have defined an abstract module for Singleton behavior, and the specific connector singleton isntances.

My problem : everytime the Rails server crash (500 error, localhost), it seems I'm losing the @client instance variable of the connector

module ServiceConnector    extend ActiveSupport::Concern      included do      include Singleton      @activated = false      @activation_attempt = false      @client = nil        def client        @client      end        def service_name        self.class.name.gsub('Connector', '')      end        def activate        @activation_attempt = true        if credentials_present?          @client = service_client          @activated = true        end        status_report      end    class MyConnector    include ServiceConnector    @app_id = nil    @api_key = nil      def credentials_present?      @app_id.present? and @api_key.present?    end      def service_client      ::MyService::Client.new(        app_id: @app_id,        api_key: @api_key      )    end      def set_credentials(id, key)      @app_id = id      @api_key = key    end  

I initialize my singleton in a Rails initializer

#config/initializers/my_connectors.rb  my_service = MyConnector.instance  if my_service_should_be_activated?    my_service.set_credentials(      Rails.application.secrets.app_id,      Rails.application.secrets.api_key    )    my_service.activate  end    def some_action_on_client    client.push_event(...)  end  

The set of events

rails s  ...  # MyConnector client Online and working fine  ...  # error 500 on some controller  # (next client request)  # MyConnector @client variable mysteriously set to nil  

Apply css on form collection

Posted: 30 Aug 2016 08:27 AM PDT

I'd like to apply this style on my collection :

  .tag-wrapper      %ul        %li.class_1.class_2         = tag.name  

This is my current code with the collection I'd like to style (see the end of the form) :

 = simple_form_for @recipe, html: {multipart: true} do |f|    - if @recipe.errors.any?      #errors        %p          = @recipe.errors.count          prohibited this recipe from being saved:        %ul          - @recipe.errors.full_messages.each do |message|            %li= message    .row      .panel-body        = f.input :title, input_html: {class: 'form-control'}        = f.input :description, placeholder: 'Dites nous ce que vous aimez dans cette recette ? où l\'avez-vous découverte ? avec quoi l\'accompagnée vous ? ...', input_html: {class: 'form-control'}        = f.input :image, input_html: {class: 'form-control'}          .tag-wrapper          = f.input :my_field, :as => :check_boxes, :collection => @tags.map{|tag| tag.name}  

I don't know how to manage collection. I should isolate each tag to display it in li then add it class_1 and class_2 but I don't know how. Here is the output if it coud help

Output

.tag-wrapper {      background: white;      width: 500px;      margin: 0 auto;      margin-top: 30px;      padding: 30px 40px;      text-align: center;      border-radius: 5px;      box-shadow: 0px 3px 3px 0px rgba(50, 50, 50, 0.4);  }    * {      margin: 0;      padding: 0;  }    * {      -webkit-box-sizing: border-box;      -moz-box-sizing: border-box;      box-sizing: border-box;  }    * {      margin: 0;      padding: 0;  }    * {      -webkit-box-sizing: border-box;      -moz-box-sizing: border-box;      box-sizing: border-box;  }  user agent stylesheetdiv {      display: block;  }
<div class="tag-wrapper">    <div class="input check_boxes optional recipe_all_tags">           <label class="check_boxes optional">All tags</label>      <span class="checkbox">        <label for="recipe_all_tags_vgtalien">          <input class="check_boxes optional tag fa fa-plus" type="checkbox" value="Végétalien" name="recipe[all_tags][]" id="recipe_all_tags_vgtalien" aria-hidden="true">Végétalien        </label>      </span>      <span class="checkbox">        <label for="recipe_all_tags_sans_lait">          <input class="check_boxes optional tag fa fa-plus" type="checkbox" value="Sans_lait" name="recipe[all_tags][]" id="recipe_all_tags_sans_lait" aria-hidden="true">Sans_lait        </label>      </span>    </div>  </div>

Rails not passing the DB Query on search form

Posted: 30 Aug 2016 07:21 AM PDT

Here what looks better, this is the log, its passing the param, but its not passing a query with that param

Started GET "/items?utf8=%E2%9C%93&search=blanca" for 65.34.251.106 at 2016-08-30 03:55:51 +0000  Processing by ItemsController#index as HTML  Parameters: {"utf8"=>"✓", "search"=>"blanca"}  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1  [["id", 3]]  Item Load (0.3ms)  SELECT  "items".* FROM "items" LIMIT 50 OFFSET 0  Item Load (0.2ms)  SELECT  "items".* FROM "items"  ORDER BY "items"."id" ASC LIMIT 1 OFFSET 0  Rendered items/_items.html.erb (3.2ms)  Rendered items/index.html.erb within layouts/application (4.9ms)  

This is the controller:

def index   @items = Item.search(params[:search])  end  

and this is the model:

def self.search(search)   Item.where("nombre LIKE ?", "%#{search}%")  end  

and the search form in the view:

<%= form_tag items_path, :method => 'get', :id => "items_search" do %>   <p>    <%= text_field_tag :search, params[:search], class: "form-control" %>    <%= submit_tag "Search", :name => nil, class: "btn btn-danger" %>   </p>    <div id="items"><%= render 'items' %>  </div>  <% end %>   

I have a _items.html.erb file which has the items to render, that part works because no matter my input on the search bar, it always shows all the items

How to store global api keys in Rails

Posted: 30 Aug 2016 07:35 AM PDT

I have a global api key for authenticating the requests to my server's api.

So the api key has to be stored somewhere in my rails application or on the server.

After a quick search, most people seem to recommend to store your keys in a .yml file and load it in your application. They claim that this is safe because the .yml file is not checked to git/source control.

Obviously you should add the .yml file to the .gitignore, otherwise it will be added git.

But If you do that, then how can the file be loaded after deployment(capistrano) if the .yml file isn't checked in to git and doesn't exist on the server?

Here is an example railscast that demonstrates storing the keys in .yml files:

http://railscasts.com/episodes/85-yaml-configuration-file?autoplay=true

Angular not rendering ng-view if cookies are not set

Posted: 30 Aug 2016 07:14 AM PDT

Very simple, but tricky bug.

This are my controller settings:

angular    .module(...)    .config(...)    .config('RealDispatchesRouter')    .controller('RealDispatchesCtrl', RealDispatchesCtrl)    RealDispatchesRouter.$inject = ['$routeProvider', '$locationProvider'];  function RealDispatchesRouter($routeProvider, $locationProvider) {    $routeProvider.when('/', {      templateUrl: '/angular/templates/realDispatches.controller.html',      controller: 'RealDispatchesCtrl',      controllerAs: 'vm',      reloadOnSearch: false    });    $locationProvider.html5Mode(true);  }    RealDispatchesCtrl.$inject = ['User', ...];  function RealDispatchesCtrl(User, ...) {...}  

The problem is that if I erase the only cookie that I see to have registered, called _session_id, from chrome, then the ngView is not rendered:

<div>    <!-- ngView: -->  </div>  

How to stub out Paperclip::AdapterRegistry::NoHandlerError?

Posted: 30 Aug 2016 07:13 AM PDT

I'm unit testing a controller. Looks like some magic goes on with paperclip with nested resources. Whenever upload_attributes: [:asset] is passed in the params, paperclip somehow gets triggered.

How to stub out the paperclip magic whenever the asset attribute is sent in the params?

Controller:

  def create      render json: {}    end      private      def user_upload_params      params.require(:price_patch_upload).permit(        :status,        upload_attributes: [:asset]      )    end  

Controller Spec:

let(:params) do    {      user: {        upload_attributes: { asset: "file" } # change 'asset' to anything else and no error      }    }  end        it "works" do      post :create, params      expect(response).to have_http_status(:created)    end  

Result:

result error

^^^ How to stub this out?

To get values from 2D array

Posted: 30 Aug 2016 07:53 AM PDT

I have used this query to retrieve the dates for one particular user's approved leaves -

LeaveRequest.where(user_id: 6).where(status: 1).pluck(:from_date, :to_date)  

and I'm getting this array as result -

[[Mon, 12 Sep 2016, Fri, 16 Sep 2016], [Tue, 06 Sep 2016, Tue, 06 Sep 2016], [Thu, 01 Sep 2016, Fri, 02 Sep 2016], [Tue, 30 Aug 2016, Wed, 31 Aug 2016]]   

what I want is to fetch all the dates as well as the dates between 12 Sep 2016 and 16 Sep, 2016 (13th 14th and 15th).

Attempting to iterate with ruby thru 4 twitter bootstrap columns

Posted: 30 Aug 2016 07:58 AM PDT

enter link description hereI am attempting to iterate over a post object, and displaying its body attribute in 4 columns, as to behave like so:

<div class='container-fluid'>    <div class='row'>      <div class='col-lg-3'><%= *post.body* %></div>      <div class='col-lg-3'><%= *post.body* %></div>      <div class='col-lg-3'><%= *post.body* %></div>      <div class='col-lg-3'><%= *post.body* %></div>    </div>    <div class='row'>      <div class='col-lg-3'><%= *post.body* %></div>      <div class='col-lg-3'><%= *post.body* %></div>      <div class='col-lg-3'><%= *post.body* %></div>      <div class='col-lg-3'><%= *post.body* %></div>    </div>  </div>  

I have tried the following:

<div class='container-fluid'>    <% @posts.each_slice(4) do |four_posts| %>      <div class="row">        <% four_posts.each do |post| %>          <div class="col-lg-3">            <%= post.body %>          </div>        <% end %>       </div>     <% end %>   </div>  

The issue I'm having is that the 'body' content is running in to the adjoining column. Does anyone have any recommendations?

ActiveRecord::StatementInvalid in Hr#internal_employee_page

Posted: 30 Aug 2016 07:29 AM PDT

I am learner ruby on rails,I want to join two model(tables). User.rb(users table)

class User < ActiveRecord::Base has_many :offer_letters end  

OfferLetter.rb(offer_letter table)

class OfferLetter < ActiveRecord::Base belongs_to :user end  

HrController(hr_controller.rb)

class HrController < ApplicationController      def internal_employee_page          @employees = OfferLetter.joins(:user).where(:id => :candidate_id)         end  

end

when run my code I got error "Mysql2::Error: Unknown column 'offer_letters.user_id' in 'on clause': SELECT offer_letters.* FROM offer_letters INNER JOIN users ON users.id = offer_letters.user_id WHERE offer_letters.id = NULL"

<div id="job_details">      <% @employees.each do |emp| %>         <%= render partial: "hr/employee_details", locals: {emp: emp} %>      <% end %>                 </div>  

Error in this line : <% @employees.each do |emp| %> So tell me where i am wrong

when i run ruby and rails code in sublime text i get an error [on hold]

Posted: 30 Aug 2016 07:02 AM PDT

here is the error when i wanted to build the project

please tell how to set this problem

C:/test-install/test.rb:1:in <main>': undefined methodput' for main:Object (NoMethodError)

Test Auth0 Login with RSpec in Rails

Posted: 30 Aug 2016 07:00 AM PDT

I'm using Auth0 for authentication in my rails app. I need to write some feature tests for login and signup. I can't seem to find something concrete on how to do this with rspec and capybara.

Tried doing something along the lines explained in this gist but it still doesn't work. If someone has had experience with rspec feature tests with Auth0 I'd appreciate if you would guide me in the right direction.

Thanks!

Customizable Button - Ruby on Rails

Posted: 30 Aug 2016 07:00 AM PDT

My website has several individual pages about courses and I need to create a button with a specific link for each course. I wanted it to show on every course page and want that the link can be changed on the administration framework by all admins and in case there's not a specific link, would show a default link. Any sugestions about how can I make this happen?

I know this probably sounds confusing, apologies for my english.

Thank you!

Rails 4.2 ActionController:BadRequest custom error message

Posted: 30 Aug 2016 07:07 AM PDT

I want to return from my controller if either a validation failed or a parameter is missing with 400 - bad request. So in my controller if have

if params["patch"].nil? then    raise ActionController::BadRequest.new( "The Json body needs to be wrapped inside a \"Patch\" key")  end  

and i catch this error in my Application Controller with:

rescue_from ActionController::BadRequest, with: :bad_request      def bad_request(exception)    render status: 400, json: {:error => exception.message}.to_json  end  

But it seems like i cannot add custom messages when raising ActionController::BadRequest. Because when passing an invalid body the response is only {"error":"ActionController::BadRequest"} and not the hash i provided.

In the console i get the same behaviour. raise ActiveRecord::RecordNotFound, "foo" indeed raises ActiveRecord::RecordNotFound: foo.

But raise ActionController::BadRequest, "baa" results in

ActionController::BadRequest: ActionController::BadRequest

How can i add custom messages to the BadRequest exception?

fetch data from db based on static set in rails

Posted: 30 Aug 2016 07:34 AM PDT

I want to fetch data from db based on static set in rails

{  data: ['data1','data2']  }  

I have a data table with column values from the static data(data model)

id| Name|    1 | data1    2 | data2    3 | data3  

I have another table which is related to the data table and spl_value column(SPL model)

id | data_id | spl_value    1  |   1     |   x    2  |   2     |   x    3  |   2     |   y    4  |   4     |   z  

How do i fetch spl_value from the static data?

The expected Result is

id | Name    | spl_value    1  |   data1 |   x    2  |   data2 |   x    3  |   data2 |   y  

Rails Version is 3

how can i optimise my spreadsheet report generation logic in rails?

Posted: 30 Aug 2016 06:39 AM PDT

Here is the code currently i am using. its taking long time to generate the report. it seams there are so many database queries that are happening in loop in my rails application. how can i reduce my database queries, by refactoring the existing code so that a quick and nicely formatted report i can generate?

def generate_report          @company = company.find("some id")      book = Spreadsheet::Workbook.new        sheet1 = book.create_worksheet :name => 'Report'          if params[:emps] == "Specific Users"       @employees = @company.employees.where("id in (?)", params[:filter_values]).includes(:department).includes(:location)        elsif params[:emps] == "Some Users"       criteria = params[:search_values]       criteria = criteria.split("_").last.to_i       if params[:search] =="Department"         @employees = @company.employees.where("department_id = ?", criteria).includes(:department).includes(:location)       end         if params[:search]=="Location"         @employees = @company.employees.where("location_id = ?", criteria).includes(:department).includes(:location)       end          elsif params[:emps] == "All Users"       @employees = @company.employees.includes(:department).includes(:location)        end             align_center = Spreadsheet::Format.new({                                              :horizontal_align => :centre,                                          })              make_bold = Spreadsheet::Format.new   ({                                               :horizontal_align => :centre,                                              :weight           => :bold,                                              :size             => 8,                                                                                       })              make_bold_color = Spreadsheet::Format.new   ({                                              :horizontal_align => :centre,                                              :weight           => :bold,                                              :size             => 8,                                              :color=> :white,                                              :pattern => 1                                          })        d1 = params[:from_date].to_date        d2 = params[:to_date].to_date        sno = 0        @employees.each_with_index do |emp, i|      i = i + (i*6) if i > 0      sno = sno +  1         sheet1[i+1,0] = sno         sheet1.row(i+1).set_format(0, align_center)          sheet1[i+1,1] = emp.employee_code         sheet1.row(i+1).set_format(1, align_center)          sheet1[i+1,2] = emp.name         sheet1.row(i+1).set_format(2, make_bold)          sheet1[i+1,3] = emp.location.location_name if emp.location # here will this make a new query again  just beacuase i used "if" statement ?           sheet1[i+2,2] = emp.department.department_name if emp.department # here will this make a new query again  just beacuase i used "if" statement ?         sheet1[i+3,2] = emp.post                sheet1.row(i+1).set_format(3, align_center) # how can i remove this formatting statements from this loop? can we format cells with static coding?          sheet1.row(i+1).set_format(4, align_center)         sheet1.row(i+2).set_format(2, align_center)         sheet1.row(i+3).set_format(2, align_center)             sheet1[i+1,4] = "Check-In"          sheet1[i+2,4] = "Check-Out"         sheet1[i+3,4] = "Duration"           sheet1[i+4,4] = "Status"         sheet1[i+5,4] = "Shift_code"               punch_records = emp.in_outs.where('date >= ? and date <= ?', d1, d2)# can i optimise this query with respect to my above queries?         total_days_count = (d2-d1).to_i + 1           punch_records.each_with_index do |punch_rec,j|          if !punch_rec.nil?        sheet1[i+1,j+5] = punch_rec.check_in.in_time_zone(punch_rec.time_zone).strftime("%I:%M %P")    if !punch_rec.check_in.nil?        sheet1[i+2,j+5] = punch_rec.check_out.in_time_zone(punch_rec.time_zone).strftime("%I:%M %P")   if !punch_rec.check_out.nil?      end      sheet1[i+3,j+5] = punch_rec.duration  if punch_rec      sheet1[i+4,j+5] = punch_rec.nil? ? "" : punch_rec.status      sheet1[i+5,j+5] = punch_rec.nil? ? "" : punch_rec.shift_id       end  end  end  

my model associations are like this.

employee has many in_outs, and in_outs belongs to employee.

location has many employees, employee belongs to location.

department has many employees, employee belongs to department.

Rails 5 - ActiveAdmin can't use current_admin

Posted: 30 Aug 2016 06:36 AM PDT

here is my problem:

I need an Admin system for A Ticket System, I already made the User Table via devise and the Admin Table, I juste added Active Admin after already created my own ticket system etc but now I wanna user ActiveAdmin, SO:

I installed it correctly, I can connect with my Admin Table in it, and I just created my "Tickets" part, which gets all my tickets correctly, the tricky part is that I need to get the current_admin to display only the tickets from his service (commercial or technical..), but I can't access the current_admin method as it is defined in the initializer, not the current_admin_user or current_user or whatever the method could be named.

I give you the code needed for good diagnostic:

config/initializer/active_admin.rb:

config.current_user_method = :current_admin    config.authentication_method = :authenticate_admin!  

app/admin/ticket.rb

ActiveAdmin.register Ticket do    config.batch_actions = false      if current_admin.service == "tech"        scope :to_do_tech      scope :in_progress_tech      scope :done_tech    else      scope :to_do_com      scope :in_progress_com      scope :done_com    end          index do      ...      ...      ...  

And That's what raise the error:

undefined local variable or method `current_admin' for #<ActiveAdmin::ResourceDSL:0x007fd4b0c08988>  

I Already saw and tried a bunch of solution which worked for others but I just can't make it works here..

Hope someone have already used it on Rails 5 and could help me cause i'm out of ideas.

How to require jquery-waypoints-rails gem in application.js

Posted: 30 Aug 2016 07:35 AM PDT

My quetion is pretty much that, I can't find a way to require waypoints.js from the gem jquery-waypoints-rails inside my application.js. Thanks in advance.

Database architecture for payment management application

Posted: 30 Aug 2016 06:28 AM PDT

              Items -> ReservationWithItems -> Checkout -> Payment -> User  Course -> Attendes -> RegistrationForCourse -> Checkout -> Payment -> User                                    YearlyFee -> Checkout -> Payment -> User  

I want to create application with handles reservations, yearly fees and training courses in my mountain club. I would like to organize my code to use Checkout class which will collect products like reservation or yearly fee or registration for course and then I will be able to create payment for them.

Below is my idea how to achieve that but I am not sure if I should use polymorphism here.

Db::Item(name:, cost:)    has_many :reservations, through: :reservations_items    Db::ReservationsItems    belongs_to :item    belongs_to :reservation    Db::Reservation(description:, state:, start_date:, end_date:)    has_many :items, through: :reservations_items    belong_to :payable, polymorphic: true    Db::Checkout    has_many :reservations, as: :payable    has_many :yearly_fees, as: :payable    has_one :payment    belongs_to :user    Db::Payment    belongs_to :checkout    -----    Db::YearlyFee(cost:, :year)    belong_to :payable, polymorphic: true  

Are there somewhere best practices or examples for this kind of systems?

How can I return a Json in controller action

Posted: 30 Aug 2016 06:29 AM PDT

I have this function in my controller:

gerencia.pay_charge(params: params, body: payment)  

This function returns:

{"code"=>200, "data"=>{"barcode"=>"03399.75039 21000.000006 74992.301015 6 69020000002250", "link"=>"https://exmaple.com.br/emissao/110276_19_NAEMAL1/A4XB-110276-74992-XILE0", "expire_at"=>"2016-08-30", "charge_id"=>97611, "status"=>"waiting", "total"=>2250, "payment"=>"banking_billet"}}   

How can I send it in json format?

I have the example in php but I don't know how do it in rails.

In php is this:

$payment = $apiGN->payCharge($params, $paymentBody);  echo json_encode($payment);  

Rails filtered parameters

Posted: 30 Aug 2016 06:16 AM PDT

I am migrating my 4.2 app into Rails 5 and I run into a strange problem. When I try to log in via this:

<%= password_field_tag :password %>  

I got [FILTERED] log in server console, but I got params[:pasword] => "*****" in controller. Which is of course not matching password (I am using BCrypt).

password encrypting:

  def encrypt_password(pass)      BCrypt::Engine.hash_secret(pass, password_salt)    end  

When I pass string "*****" into this method I got the same result as if I pass params[:password] there, which means the controller doesn't know about inserted password but gets only 5 asterisks. If I try this on my master branch with Rails 4.2.7 then in controller I can correctly see inserted password (in log there is "[FILTERED]" correctly).

Do I miss some new feature about filtering parameters in Rails 5???

EDIT: I tried

render plain: params.to_yaml  

I got:

--- !ruby/object:ActionController::Parameters  parameters: !ruby/hash:ActiveSupport::HashWithIndifferentAccess    utf8: "✓"    authenticity_token: 6/qK4IYcTL3lDTLNEICMmrcBhR5FJy6r3QNN5hYXNQTOqrdwtcX5aye4wN3AIz6PSmsMSf6V7/z8fmUo7KUXyQ==    login: doktor    password: "*****"    commit: Přihlaš  permitted: false  

Call method from controller in view (ROR)

Posted: 30 Aug 2016 06:07 AM PDT

I wanna call method from controller in view using the following code:

<%= memmory("#{broker.id}") %>  

but its giving error "undefined method `memmory' for #<#:0xb3bf71e8>"

Wicked PDF not rendering footer when PDF is created in model

Posted: 30 Aug 2016 05:55 AM PDT

I'm using the wicked PDF gem to generate PDFs for my application. I have had some logic in my controller which has been generating PDFs with footers and page numbers for some time.

I need to now generate this PDF in my model and since moving the controller render pdf code to the model, it hasn't been rendering a footer or proper margin.

This is the code in my controller which works:

WickedPdf.new.pdf_from_string(      render  :pdf => "#{@user.id}_#{@paper.data["statementDate"]}",              :template => "statements/monthly_statement_templates/#{@paper_template}",              :footer => { :html => { template: 'statements/monthly_statement_templates/footer.pdf.erb' }},              :title => "#{@paper.data["statementDate"]} Statement",              :locals => { :statement => @paper.data },              :margin => {                :bottom => 20,                :top => 20              }  

I've moved the code to the model. It looks like the following:

av = ActionView::Base.new()  av.view_paths = ActionController::Base.view_paths    # Need these in case the view constructs any links or references any helper methods.  av.class_eval do    include Rails.application.routes.url_helpers    include ApplicationHelper  end    statement_pdf = WickedPdf.new.pdf_from_string(        av.render :pdf => "#{statement.id}",          :template => "statements/monthly_statement_templates/#{statement_template}",          :footer => { :html => { :template => 'statements/monthly_statement_templates/shared/footer.pdf.erb' }},          :locals => { :statement => statement.data },          :margin => { :bottom => 20, :top => 20 }      )  

When comparing the two PDFs all of the data and styles within the template are the same. However, when rendering the PDF from the model it is not including the footer which has some text and page numbers.

My footer is as follows:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">    <head>      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />      <%= stylesheet_link_tag "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" %>      <style type="text/css">        .legal { font-size: 8px; }      </style>      <script>        function number_pages() {          var vars={};          var x=document.location.search.substring(1).split('&');          for(var i in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);}          var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];          for(var i in x) {            var y = document.getElementsByClassName(x[i]);            for(var j=0; j<y.length; ++j) y[j].textContent = vars[x[i]];          }        }      </script>    </head>      <body onload="number_pages()">      <div class="container">        <div class="row">          <div class="col-xs-12">            <div class="col-xs-9 legal">            </div>            <div class="col-xs-3 pull-right legal">              <small>Page <span class="page"></span> of <span class="topage"></span></small>          </div>        </div>      </div>    </body>  </html>  

No comments:

Post a Comment