Wednesday, December 28, 2016

date_select in rails , How do I get the selected value? | Fixed issues

date_select in rails , How do I get the selected value? | Fixed issues


date_select in rails , How do I get the selected value?

Posted: 28 Dec 2016 07:23 AM PST

My view file is below.

             <div class="field">                     <%= f.label :deadline , class:"form-label"  %><br />                     <%= f.date_select( :deadline , use_month_numbers: true , start_year: (Time.now.year) , end_year: (Time.now.year+1) , start_month: (Time.now.month) , end_month: (12) , start_day: (Time.now.day) , end_day: (days_in_month(Time.now.month)) , default: Date.new(Time.now.year , Time.now.month , Time.now.day) , date_separator: '/' ) %>               </div>  

days_in_month(Time.now.month) is helper method.

def days_in_month(month, year = Time.now.year)     common_year_days_in_month = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]     return 29 if month == 2 && Date.gregorian_leap?(year)     common_year_days_in_month[month]  end  

In this case , when user selects 'month', 'day' doesn't change. For example, in 2016-12-28, The page shows 2016/12/28 in default, and the end_day is 31 because 12 month has 31 days. But although user selects 11 month , end_day is 31 because 12 month has 31 days. in the case , I want to show 30 in end_day. Please help me...

How to render a js.erb with the same name as a member action in Rails?

Posted: 28 Dec 2016 07:09 AM PST

I'd think this would go automatically, as I have already managed to do so for my destroy action, but no JS in activated.

My controller action looks like this:

  def visability_toggle      @picture = Picture.find(params[:id])      @picture.toggle! :visable        respond_to do |format|        format.js { render :action => 'visability_toggle' }      end    end  

And for now my pictures/_visability_toggle.js.erb that I would like to match my controller looks like this:

alert('Picture id: #{@picture.id}');  

The action itself works. Also this JS is correct and worked when I added it with render js: ... in the controller action.

Variables are global with SASS but not SCSS

Posted: 28 Dec 2016 06:53 AM PST

I have my application.css.scss set like this:

@import "base/variables";  @import "./application/application";  

Like the documentation says I am not using Sprockets' directives (require, require_tree, and require_self) at all so I expect my variables defined inside of base/_variables.scss to be globals and available for my /application/application.scss file but it's not the case:

#content {    margin-top: $big;  }  

Will return the error Undefined variable: "$big".

I've tried the same thing with SASS by naming by files application.css.sass and /application/application.sass and while the variables now do seems to be globals I'll like to keep using the SCSS syntax, I've tried that by setting config.sass.preferred_syntax = :scss but I'm still being asked for Sass.

Of course I could just import my variables file everytime I need my variables but that would go against the DRY principle.

Is that possible to use the SCSS syntax while making my variables globally available? What am I missing here? Thanks in advance.

Photo preview is shown but photo is not saved in form: using Carrierwave and preview photo with JS

Posted: 28 Dec 2016 06:39 AM PST

I'm trying to update a profile picture from a user through a (edit)-form. I want to show the user which photo it is trying to upload, so I've used JS to preview the selected photo. The problem is that the preview is showing, but the new photo isn't saved through the form.

Any ideas on what I might have missed?

edit.html.erb

     <%= f.inputs do %>         <% if @user.photo? %>          <div id="photo_edit">           <img id="img_prev" class="profile_photo_edit" src="<%= current_user.photo %>">           <label id="photo-edit-button">           <input type='file' onchange="readURL(this);" />           <%= f.file_field :photo %>           <%= f.hidden_field :photo_cache %>           <span>Wijzig foto</span>         </label>       </div>       <% else %>       <div id="photo_edit">         <%= image_tag "PICA.jpg", :id => "img_prev", :class => "profile_photo_edit"%>         <label id="photo-edit-button">           <input type='file' onchange="readURL(this);" />           <%= f.file_field :photo %>           <%= f.hidden_field :photo_cache %>           <span>Wijzig foto</span>         </label>       </div>       <% end %>  

photo-preview.js

    function readURL(input) {       if (input.files && input.files[0]) {          var reader = new FileReader();            reader.onload = function (e) {            $('#img_prev')            .attr('src', e.target.result)            .width(100)            .height(100);          };            reader.readAsDataURL(input.files[0]);        }      }  

users_controller

    def user_params              params.require(:user).permit(:first_name, :last_name, :current_position, :position_description, :email, :phonenumber, :linkedin, :skype, :location_id, :location_specs, :photo, :photo_cache)      end  

Rails prawn chart not rendered completely at the bottom of the page

Posted: 28 Dec 2016 06:32 AM PST

I am creating a pdf report in order to show some data using the "squid" gem. This would allow me to display charts in my pdf. The only issue i found is that when the chart does not fit at the bottom of the page then it looks rendered partially which does not look good at all. Any idea how can i fix this?

enter image description here

Here is the code i am using to render the charts

require 'squid'    class SurveyPdf < Prawn::Document    def initialize(survey, view)      super()      font "#{Rails.root}/app/assets/fonts/roboto-condensed.ttf"        @survey = survey      @view = view      questions    end      def questions      @survey.questions.each do |question|        text "#{question.title}", size: 20        text "Answers #{question.answers.size}", size: 15        if ["single", "select"].include? question.question_type.prefix          if question.answers.choice_counter.any?            chart choices: question.answers.choice_counter          end        end        if question.question_type.prefix == "image"          if question.answers.image_counter.any?            chart images: question.answers.image_counter          end        end        if question.question_type.prefix == "multiple"          if question.answers.multiple_choice_counter.any?            chart choices: question.answers.multiple_choice_counter          end        end        if question.question_type.prefix == "raiting"          move_down 5          if question.answers.any?            text_box "Average rating", size: 12, width: 120, :at => [0,  cursor - 2]            text_box "#{average_rating(question.answers.rating_average)}", size: 12, width: 120, :at => [4 * 30,  cursor - 2]          else            text_box "Average rating", size: 12, width: 120, :at => [0,  cursor - 2]            text_box "0", size: 12, width: 120, :at => [4 * 30,  cursor - 2]          end        end      end    end  end  

Stripe: no such token

Posted: 28 Dec 2016 07:18 AM PST

I keep getting this error while trying to pay with my stripe integration:

Stripe::InvalidRequestError (No such token: tok_19Vh25DGnBus....):  

Here's my Ruby on Rails integration:

config/application.yml (I use Figaro gem to handle environment variables):

STRIPE_SECRET_KEY      :"sk_test_xxxxxxxxxxxxx"                                          STRIPE_PUB_KEY         :"pk_test_xxxxxxxxxxxxx"  

config/initializers/stripe.rb:

Rails.configuration.stripe = {      :publishable_key => ENV['STRIPE_PUB_KEY'],      :secret_key      => ENV['STRIPE_SECRET_KEY']  }    Stripe.api_key = Rails.configuration.stripe[:secret_key]  

controllers/api_controller.rb:

require 'stripe'    charge = Stripe::Charge.create(    # -> Line of the error              :amount => price,              :currency => "gbp",              :source => token,              :description => ""          )  

In the front-end side I use angular and the module angularPayments:

$window.Stripe.setPublishableKey("pk_live_xxxxxxxxxxx");      $scope.handleStripe = function(status, response){        $rootScope.loader = true;        var email = $scope.email;          $scope.email = "";        $scope.number = '';        $scope.expiry = null;        $scope.cvc =  '';          if(response.error) {            $scope.paid= false;            $scope.message = "The card you have inserted is not valid.";            $rootScope.loader = false;        } else {            var data = {                'invoice_url' : $stateParams.invoiceUrl,                'token' : response.id,                'price': $scope.invoice.price,                'email': email            };              $http.post(URL.url + 'send_payment', data).then(function(res){                if(res.data.error){                    $scope.paid= false;                    $scope.message = res.data.message;                    $rootScope.loader = false;                }else{                    $scope.paid= true;                    $rootScope.temp_modal = true;                    $scope.message = res.data.message;                }                $rootScope.loader = false;            });          }    };  

I checked and all the keys are correct and match the account that I'm using...In test mode everything worked fine...what am I missing?

How to add if condition inside this helper method?

Posted: 28 Dec 2016 06:24 AM PST

I am not able to give the if condition inside this method. Please help me solve this problem.

def published_comment              "<li>                <div id='comment_#{@comment.anchor}' class='comment #{@comment.state}' data-comment-id='#{@comment.to_param}'>                  <div>                    #{ avatar }                    #{ userbar }                    <div class='cbody'>#{ @comment.content }</div>                    #{ reply }                      #{ if controller.try(:current_user).try(:admin?) }                      #{ approved_comment }                     #{ end }                     </div>                </div>                <div class='form_holder'></div>                #{ children }              </li>"            end  

How to test a url which doesn't exist?

Posted: 28 Dec 2016 07:09 AM PST

I want to validate that my url in my web application returns 404 Not found. I know it doesn't exist, but I need to confirm that via tests by Rspec. How? This doesn't work:

it "404" do    get "/some_url_404"    expect(response.status).to eq 404  end  

The test itself fails with:

ActionController::RoutingError: No route matches [GET] "/some_url_404"

Rails with mysql cannot create json type column

Posted: 28 Dec 2016 06:22 AM PST

I have created Rails(3.2) application with mysql(5.7.16) backend. I can't add json type column when creating table but I can able to add json column by new migration. I have used following code in create table migration, What was wrong here ?

class CreateShoppingCartItemSpecialInfos < ActiveRecord::Migration    def change      create_table :shopping_cart_item_special_infos do |t|        t.integer :shopping_cart_checkout_option_id        t.json :special_info          t.timestamps      end    end  end  

sort data pulled from API with Javascript

Posted: 28 Dec 2016 05:37 AM PST

I am currently pulling data from an API using ROR and displaying the results in my app using Jquery Masonry. I am trying to now allow a user to sort the data pulled in a few different ways after the page loads. I would like someone to be able to sort data by: "this week", "next week", and "next month". Also, I would like to create some pre-defined filters that users can select to futher filter their results, such as: "sports", "outdoors", "fitness", "hiking", "running", "cycling" etc. Is there a way to run a script that searches the page for these certain keywords and then eliminates the results that do not match? I have dove in JS @ all so any help would be greatly appreciated.

<nav class="navbar navbar-default">    <div class="container-fluid">      <div class="navbar-header">        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">          <span class="sr-only">Toggle navigation</span>          <span class="icon-bar"></span>          <span class="icon-bar"></span>          <span class="icon-bar"></span>        </button>        <a class="navbar-brand" href="/" style="padding:0">          <img src="../images/logo.png" class="logo">        </a>      </div>      <!-- Collect the nav links, forms, and other content for toggling -->      <div class="collapse navbar-collapse nav-search-from" id="bs-example-navbar-collapse-1">        <form role="form" data-toggle="validator" action="search">          <div class="form-inline search-form">            <div class="form-group search-box">              <input type="text" name="zipcode" class="form-control input-box" placeholder="Enter Zipcode" value="<%= @zipcode %>"required>            </div>            <div class="form-group search-box">              <%= select_tag "radius", options_for_select(Radius::RADIUS, @radius), {"onChange" => "changeRadius(this)", class: "form-control"} %>            </div>            <!--<div class="form-group search-box">-->            <!--<input type="text" id="filter" class="form-control input-box" placeholder="Filter" value="<%= @keyword %>"> -->            <!--</div>-->            <div class="form-group search-box">              <button type="submit" class="search-button btn btn-success">                <i class="glyphicon glyphicon-search"></i>                <span>Search</span>              </button>            </div>          </div>        </form>      </div><!-- /.navbar-collapse -->    </div><!-- /.container-fluid -->  </nav>    <div class="content">    <div class="event-container grid">      <% if @fitness_events %>          <% @fitness_events.each do |fitness_event| %>              <div class="grid-item">                <div class="event-list-container">                  <%= link_to "Register for event", {:controller => "meetup_events", :action => "detailed_event", :event => fitness_event['id'], :zip => @zipcode, :radius => @radius }, class: "join-button btn btn-success hidden" %>                  <div class="row event-listing clearfix doc-padding">                    <p class="event-name"><%= fitness_event['name'] %></p>                    <% if fitness_event['photo'] %>                        <div class="">                          <%= image_tag fitness_event['photo'], :class => "event_photo" %>                        </div>                    <% end %>                  </div>                  <div class="row heart-time">                    <div class="col-sm-3 col-xs-3">                      <span class="glyphicon glyphicon-heart"></span>                      <%= fitness_event['yes_rsvp_count'] %>                    </div>                    <div class="col-sm-9 col-xs-9 created-time">                      <span class="glyphicon glyphicon-time"></span>                      <%= Time.at(fitness_event['time']/1000).strftime("%b %e, %I:%M %p") %>                    </div>                  </div>                  <div class="row">                    <div class="col-sm-12 col-xs-12 location">                      <% if fitness_event['venue'] %>                          <i class="glyphicon glyphicon-map-marker"></i>                          <%= fitness_event['venue']['address_1'] %>                      <% end %>                    </div>                  </div>                  <div class="row">                    <div class="col-sm-12 col-xs-12 location">                      <% if fitness_event['group'] %>                          <i class="fa fa-users"></i>                          <%= fitness_event['group']['name'] %>                      <% end %>                    </div>                  </div>                  <div class="row">                    <div class="col-sm-12 col-xs-12 description">                      <% if fitness_event['desc'] %>                          <i class="fa fa-file-text"></i>                          <%= fitness_event['desc'] %>                      <% end %>                    </div>                  </div>                  <div class="row">                    <%= link_to "Register for event", {:controller => "meetup_events", :action => "join", :event => fitness_event }, class: "join-button btn btn-success pull-right", target: "_blank" %>                  </div>                </div>              </div>          <% end %>      <% end %>        <% if @outdoor_events %>          <% @outdoor_events.each do |event| %>              <div class="grid-item">                <div class="event-list-container">                  <%= link_to "Register for event", {:controller => "meetup_events", :action => "detailed_event", :event => event['id'], :zip => @zipcode, :radius => @radius }, class: "join-button btn btn-success hidden" %>                  <div class="row event-listing clearfix doc-padding">                    <p class="event-name"><%= event['name'] %></p>                    <% if event['photo'] %>                        <div class="">                          <%= image_tag event['photo'], :class => "event_photo" %>                        </div>                    <% end %>                  </div>                  <div class="row heart-time">                    <div class="col-sm-3 col-xs-3">                      <span class="glyphicon glyphicon-heart"></span>                      <%= event['yes_rsvp_count'] %>                    </div>                    <div class="col-sm-9 col-xs-9 created-time">                      <span class="glyphicon glyphicon-time"></span>                      <%= Time.at(event['time']/1000).strftime("%b %e, %I:%M %p") %>                    </div>                  </div>                  <div class="row">                    <div class="col-sm-12 col-xs-12 location">                      <% if event['venue'] %>                          <i class="glyphicon glyphicon-map-marker"></i>                          <%= event['venue']['address_1'] %>                      <% end %>                    </div>                  </div>                  <div class="row">                    <div class="col-sm-12 col-xs-12 location">                      <% if event['group'] %>                          <i class="fa fa-users"></i>                          <%= event['group']['name'] %>                      <% end %>                    </div>                  </div>                  <div class="row">                    <div class="col-sm-12 col-xs-12 description">                      <% if event['desc'] %>                          <i class="fa fa-file-text"></i>                          <%= event['desc'] %>                      <% end %>                    </div>                  </div>                  <div class="row">                    <%= link_to "Register for event", {:controller => "meetup_events", :action => "join", :event => event }, class: "join-button btn btn-success pull-right", target: "_blank" %>                  </div>                </div>              </div>          <% end %>      <% end %>        <% if @sports_events %>          <% @sports_events.each do |event| %>              <div class="grid-item">                <div class="event-list-container">                  <%= link_to "Register for event", {:controller => "meetup_events", :action => "detailed_event", :event => event['id'], :zip => @zipcode, :radius => @radius }, class: "join-button btn btn-success hidden" %>                  <div class="row event-listing clearfix doc-padding">                    <p class="event-name"><%= event['name'] %></p>                    <% if event['photo'] %>                        <div class="">                          <%= image_tag event['photo'], :class => "event_photo" %>                        </div>                    <% end %>                  </div>                  <div class="row heart-time">                    <div class="col-sm-3 col-xs-3">                      <span class="glyphicon glyphicon-heart"></span>                      <%= event['yes_rsvp_count'] %>                    </div>                    <div class="col-sm-9 col-xs-9 created-time">                      <span class="glyphicon glyphicon-time"></span>                      <%= Time.at(event['time']/1000).strftime("%b %e, %I:%M %p") %>                    </div>                  </div>                  <div class="row">                    <div class="col-sm-12 col-xs-12 location">                      <% if event['venue'] %>                          <i class="glyphicon glyphicon-map-marker"></i>                          <%= event['venue']['address_1'] %>                      <% end %>                    </div>                  </div>                  <div class="row">                    <div class="col-sm-12 col-xs-12 location">                      <% if event['group'] %>                          <i class="fa fa-users"></i>                          <%= event['group']['name'] %>                      <% end %>                    </div>                  </div>                  <div class="row">                    <div class="col-sm-12 col-xs-12 description">                      <% if event['desc'] %>                          <i class="fa fa-file-text"></i>                          <%= event['desc'] %>                      <% end %>                    </div>                  </div>                  <div class="row">                    <%= link_to "Register for event", {:controller => "meetup_events", :action => "join", :event => event }, class: "join-button btn btn-success pull-right", target: "_blank" %>                  </div>                </div>              </div>          <% end %>      <% end %>    </div>      <% if @fitness_events.empty? && @outdoor_events.empty? && @sports_events.empty? %>        <p class="no-result">No Search Result</p>    <% end %>  </div>    <script src="https://cdnjs.com/libraries/1000hz-bootstrap-validator"></script>  <script src="https://unpkg.com/masonry-layout@4.1/dist/masonry.pkgd.min.js"></script>  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/3.0.4/jquery.imagesloaded.min.js"></script>  <script>  //    var grid = document.querySelector('.grid');  //  //    $(window).load(function(){  //        $('.grid').masonry({  //            // options...  //            itemSelector: '.grid-item',  //            gutter: 10  //        });  //    });      $(window).ready(function(){          // init Masonry          var $grid = $('.grid').masonry({              // options...              itemSelector: '.grid-item',              gutter: 10          });          // layout Masonry after each image loads          $grid.imagesLoaded().progress( function() {              $grid.masonry('layout');          });      });  //    var msnry = new Masonry( grid, {  ////        // options...  ////        columnWidth: 20,  ////        fitWidth: true,  //        itemSelector: '.grid-item',  //        gutter: 10  //    });  //    $("div.grid-item").click(function() {  //        window.location=$(this).find("a").attr("href"); return false;  //    });      function changeRadius(x){          radius = x.value;      }  </script>  

Need help on link_to with on click event ruby on rails 4.2.6

Posted: 28 Dec 2016 06:43 AM PST

I'm new to Rails. If anyone could help me convert this code into a ruby link_to method:

<a href="#top" onclick=$("#menu-close").click();>Home</a>  

I tried to search google for an answer. But it made me more confuse on how to implement it on my site.

<%= link_to "Home" , {:action => "index", :controller => "welcome", :anchor => "top", :onclick => '$("#menu-close").click()' } %>   

but still it does not close the sidebar.

Here is also the script I put below the footer :

$("#menu-close").click(function(e) {     e.preventDefault();     $("#sidebar-wrapper").toggleClass("active");   });  

Filter eager-loaded has_many association

Posted: 28 Dec 2016 05:14 AM PST

Suppose I have the following two classes:

class Group    has_many :actions  end    class Action    belongs_to :group    belongs_to :user  end  

And I want to retrieve all Groups with their Actions, i.e. :

Group.includes(:actions)  

But I want to filter the loaded actions by the current user's user_id, so when iterating the 'actions' association, only the user's Actions would be returned.

I could add another association, like so:

has_many :current_user_actions, -> {where(user_id: User.current_user.id)}, class_name: 'Action'  

But the aforementioned Group query feeds a view that iterates over the 'actions' (and not 'current_user_actions') association, so that option's ruled out.

Generate elements with jQuery and Rails

Posted: 28 Dec 2016 04:45 AM PST

I am not sure how to do that. I have a model Post which I am showing when somebody hits /posts/1. Now this post belongs to someone. Which means I have another model called User. But there is more. Now a post can have a Comment. All of this works fine so far, because I am just loading everything as soon as somebody hits /posts/1. Now I would like to show all posts from the user when somebody hits /users/1. I created a view called posts/_post.html.erb and in the view of the user I have this code snippet: <%= render @posts %>. This works so far! But now I would like to show comments of every post BUT only if he hits a button called Show comments. Now this should trigger an ajax call and then show my comments.

My question here is, should I create a GET-Route where I get all of the comments from the post as JSON and then create the HTML-Elements with Javascript or is there a better version with Rails, because I already have a view called comments/_comments.html.erb? Do I really have to defined the template once in the view file and once in the Javascript?

How to handle error in event machine using transitions gem on rails?

Posted: 28 Dec 2016 04:42 AM PST

I am working on event machine (transitions gem) in rails 4.2 , I wrote a method named send_data and when state changed from pending to deliver, the send_data will be fired.

def send_data      data = { 'remote_id' => order.remote_id,               'items' => order.line_items             }      SendLineItemsToWebshop.call(data)            end  

SendLineItemsToWebshop is an another class which calls call method and waiting for some response, if response come , then event will be fired(state will be changed) , otherwise, state will be same.

require 'bunny'  require 'thread'  class SendLineItemsToWebshop    def self.call(data)      conn = Bunny.new(automatically_recover: false)      conn.start      channel = conn.create_channel      response = call_client(channel, data)      channel.queue(ENV['BLISS_RPC_QUEUE_NAME']).pop      channel.close      conn.close      self.response(response)    end      def self.call_client(channel, data)      client = RpcClient.new(channel, ENV['BLISS_RPC_QUEUE_NAME'])      client.call(data)    end      def self.response(response)      return response      JSON.parse response    end  end  

But problem is that when event deliver is called, it does not check send_data's response comes or not, it changes the state. Here is me deliver event:

event :deliver do        transitions :to => :delivered, :from => [:editing, :pending] , on_transition: [ :send_data ]      end  

But I want that if response is false or nil, transition state will not be changed. State will be changed only when response comes true. Please help me about this issue.

Rails 5: tree view using jsTree and AJAX

Posted: 28 Dec 2016 04:34 AM PST

I have controller where on dropdown select Placement for particular Media is populated:

def index    @media = Media::Media.where(company_id: user_companies)  end    def update_placements    @placements = Placements::Radios.joins(positions: :media).where('media_id = ?', params[:media_id])    @placement_array = group_placements    respond_to do |format|      format.js    end  end    def group_placements    data = @placements.group_by { |rec| rec[:adbreaks].to_date }.group_by { |d, _| d.at_beginning_of_month }.group_by { |m, _| m.at_beginning_of_year }    data.sort_by(&:first).each { |y, recs| "#{y.year}"; recs.sort_by(&:first).each { |m, recs| "#{m.strftime '%B'}"; recs.sort_by(&:first).each { |d, recs| "#{d.day}"; recs.each { |rec| "id: #{rec[:id]}" } } } }  end  

I'm a bit stuck in creating jsTree view where particular records would be loaded preferably with AJAX. My desired outcome would be something like this:

-Year    -Month      -Day       #all records related to particular day  

Example jsTree code for using AJAX is like this:

$('#tree').jstree({  'core' : {    'data' : {      'url' : function (node) {        return node.id === '#' ?          'ajax_roots.json' :          'ajax_children.json';      },      'data' : function (node) {        return { 'id' : node.id };      }    }  });  

How do I connect it together, please? Thank you for any help!

display ajax response in div in ror

Posted: 28 Dec 2016 04:38 AM PST

I am trying to display data from db using the value of a dropdown after a button is pressed through ajax. This is my ajax code:

$(function () {    $("button").click(function(){         var value2 = $('select#dropdown option:selected').val();           $.ajax({             type: "GET",              dataType: "json",             url:"/mycontroller/action2",             data: {data1: value2 },              success:function(result1){                   console.log(result1);                   result1.forEach(function(){                   $res_html = $("<div class= 'result1'>" + result1 + "</div>");                   $('#test1').append($res_html);                    $("test1").text(result1);                      })              }        })    });  });  

I have a div:

<div id= "test1"></div>  

my problem is i am unable to display data in div tag of view in ror.

Thanks in advance.

Rails: How to show items only if creator is unique?

Posted: 28 Dec 2016 07:34 AM PST

I have many users and each user has multiple projects.

Now, I want to get only one item per user.

@projects = Project.all.where(user_id is unique)

That is project should be fetched only if no other project from the same user was fetched already.

Hope I was clear with my question. I am on Rails 5.

EDIT:

I am using postgres in production.

Assets not loading in development, ruby 2.4.0 and rails 5.0.1

Posted: 28 Dec 2016 04:22 AM PST

Tried upgrading to latest rails/ruby, and now assets are not loaded in development (works in production on heroku), In development I get no route matches error for all assets.

application.rb

require_relative 'boot'    require 'rails/all'  require 'base64'      Bundler.require(*Rails.groups)    module Superapp    class Application < Rails::Application    # Rails 5 upgrade  #config.active_record.belongs_to_required_by_default = false  #config.action_controller.per_form_csrf_tokens = true  #config.action_controller.forgery_protection_origin_check = true  #config.action_mailer.perform_caching = true  ## End Rails 5 upgrade    #config.assets.initialize_on_precompile = false  config.i18n.enforce_available_locales = true    # Custom directories with classes and modules you want to be autoloadable.  # config.autoload_paths += %W(#{config.root}/extras)  config.secret_token = '';    config.assets.enabled = true  config.assets.paths << "#{Rails.root}/app/assets/fonts"     #config.action_controller.default_asset_host_protocol = :relative    #Make sure whitelist is not active  #config.active_record.whitelist_attributes = false    # Only load the plugins named here, in the order given (default is alphabetical).  # :all can be used as a placeholder for all plugins not explicitly named.  # config.plugins = [ :exception_notification, :ssl_requirement, :all ]    # Activate observers that should always be running.  # config.active_record.observers = :cacher, :garbage_collector, :forum_observer    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.  # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.   config.time_zone = 'Europe/Oslo'    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.  # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]  config.i18n.default_locale = :nb  config.i18n.fallbacks =[:nb, :en]  config.i18n.load_path = Dir[Rails.root.join('phrase', 'locales', '*.yml').to_s]   # config.middleware.insert 0, Rack::UTF8Sanitizer      # JavaScript files you want as :defaults (application.js is always included).  # config.action_view.javascript_expansions[:defaults] = %w(jquery rails)    # Configure the default encoding used in templates for Ruby 1.9.   # config.encoding = "utf-8"    # Configure sensitive parameters which will be filtered from the log file.  config.filter_parameters += [:password, :password_confirmation, :expiry_month, :expiry_year, :cvc, :cardnum]     end  end  

development.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    config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }      # 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    config.public_file_server.enabled = true    # Don't care if the mailer can't send.    config.action_mailer.raise_delivery_errors = false      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 = false    config.assets.compress = false      # 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      # Don't care if the mailer can't send    config.action_mailer.raise_delivery_errors = true    config.action_mailer.delivery_method = :letter_opener    end  

Populate join table using seeds.rb

Posted: 28 Dec 2016 04:21 AM PST

In my rails app I have three tables: users, roles, and users_roles.

In my seeds.rb file I have the following ruby code:

# create super admin role  Role.create!([{name: "Super Admin", description: "Super Admin (can do anything)"}])  # create user  User.create!([{name: "Cameron", email: "cameron.drysdale@example.com", password_digest: "$2a$10$k4FPOZlVmy.hIM5z1scFYeFc8cNcVGpq..MU0529LlSGylEqYLaqC"}])  # make user super admin  User::HABTM_Roles.create!([{user_id: 1, role_id: 1}])  

However it fails on that last line: User::HABTM_Roles.create!

How do I add the data into the join table?

adding two factor authentication to devise

Posted: 28 Dec 2016 03:59 AM PST

I tried to add two-factor-authentication to my rails-app with this gem: https://github.com/tinfoil/devise-two-factor

I used It like the example in the README. But I made a little bit more changes like this:

application_controller:

before_action :check_for_user_2fa    protected    def check_for_user_2fa      if self.controller_name != "registrations" && self.action_name != "confirm_two_factor"        return unless current_user && current_user.otp_required_for_login?        redirect_to confirm_two_factor_url, alert: "You did not confirmed your two factor authentication."      end    end  

to display the QRCode I use this script:

 def google_authenticator_qrcode(user)      issuer = 'UB'      label = "#{issuer}:#{user.email}"      data = user.otp_provisioning_uri(label, issuer: issuer)      url = "https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl=#{data}"      return image_tag(url, :alt => 'Google Authenticator QRCode')    end  

In my routes.rb I added this:

devise_scope :user do    get '/users/two_factor/confirm' => 'users/registrations#confirm_two_factor', as: :confirm_two_factor    put '/users/two_factor' => 'users/registrations#confirm_two_factor_update', as: :confirm_two_factor_update  end  

and the view to handle the auth after login:

= google_authenticator_qrcode(resource)  %h2 Hi, scan Google Authenticator QR code and enter result code below to confirm your two factor auth!  = form_tag(confirm_two_factor_update_path, :method => :put) do    = devise_error_messages!    = text_field_tag :code    = submit_tag "Log in!"  = link_to "Sign out", destroy_user_session_path, :method => :delete  

the QRCode is the right. But how can I check the right code? And how to skip the two-factor-auth for other controller?

How to delete the files/folder from git repository without deleting the Git history

Posted: 28 Dec 2016 07:36 AM PST

I need to delete the outdated folder v1 from app/controllers/api folder. Now we have updated v2 folder inside api/controllers. But I need to preserve the v1 folder git history. Any help would be highly appreciated.

Rspec inclusions like "-t visual" no longer working

Posted: 28 Dec 2016 03:16 AM PST

I am using Rails 4 and rspec-rails (3.4.2) and gems:

gem 'selenium-webdriver', '2.45.0'  gem 'capybara'  

And I wanted to add an additional parameter -t visual to my rspec test like:

rspec spec/feature/profile_spec.rb -t visual

So it could open a firefox for that, but in the rspec_helper.rb I used to be able to set a check like this:

if config.filter_manager.inclusions[:visual]    # Set my driver etc.    config.filter_manager.inclusions.delete(:visual)  else    # Something else  end  

But the check config.filter_manager.inclusions[:visual] now returns nil, and I remember it was returning true in some of my previous apps that I have tried to build.

Why inclusions are no longer detected, and how to fix this?

How to add conditional has_many associations

Posted: 28 Dec 2016 06:35 AM PST

I have following DB structure

tasks

id   name   parent_id  1    Abc    nil  2    Pqr    1  

comments

id task_id body    1   1      This is sample comment  2   1      This is another sample comment  

task.rb

has_many :comments  

comment.rb

belongs_to :task  

My requirement is to have an associations such that for the parent as well as children i should get the parent comments i.e. for both the above tasks i should get ['This is sample comment', 'This is another sample comment'] as child tasks will not have any comments.

I tried something like following but it doesn't work

task.rb

has_many :comments,  -> (o) { where(comments: {task_id: [o.id, o.parent_id]}) }  

Unexpected <tr> when looping

Posted: 28 Dec 2016 05:49 AM PST

I have an array of arrays @iterated_orders like this:

[[1, "Don", 3], [nil, nil, 4], [2, "Vri", nil]]  

And code in my view like this:

    %table        - @iterated_orders.each do |day, day_name, order_id|          - unless day.blank?            %tr              %td.day= day          %td= order_id  

I would expect it to output this html:

<tr>    <td class="day">1 Don</td>    <td>3</td>    <td>4</td>  </tr>  <tr>    <td class="day">2 Vri</td>    <td></td>    <td></td>  </tr>  

But it outputs this HTML:

<tr>    <td class="day">1 Don</td>    <td></td>  </tr>  <tr>    <td>3</td>    <td>4</td>  </tr>  <tr>    <td class="day">2 Vri</td>    <td></td>  </tr>  <tr>    <td></td>  </tr>  

Why is there an extra <tr> and is the <td> with the order_id not added to the existing <tr>?

Verify Spree promotion coupon from an external API

Posted: 28 Dec 2016 02:43 AM PST

I want to apply a coupon to my spree application but the coupon should be verified from an external API

I searched through the docs as well as tutorials but I haven't found anything which can help me

The requirement is something like this:

  • I am selling a product and I want to give a discount of 10% to members of some organization.

  • On payment page, the user will enter his email address and I want to verify that email from API provided by organization

I am referring this right now

1 . http://guides.spreecommerce.org/user/promotions.html

Bootstrap navbar collapse a links with exception not floating left

Posted: 28 Dec 2016 03:37 AM PST

Hello I want to make a float none in my application scss for all the a href from the navbar with the exception of the navbar-brand which is the "Home".

This is my application.html.erb:

 <nav class="navbar navbar-default navbar-custom">    <div class="container">      <%= link_to "Home", root_path, class: "navbar-brand" %>      <button class="navbar-toggle" data-toggle= "collapse" data-target=".navHeaderCollapse" >      <span class="icon-bar"></span>      <span class="icon-bar"></span>      <span class="icon-bar"></span>      </button>    <div class="collapse navbar-collapse navHeaderCollapse" >      <ul class="nav navbar-nav" id="top">                              <li><%= link_to "Products", products_path %></li>          <li><%= link_to "About the website", about_path %></li>          </ul>      <ul class="nav navbar-nav navbar-right">      <!-- the pull-right is like a float right -->            <% if user_signed_in? %>                        <li><a><span class="current_user"> Current user: <%= @username %> </span></a></li>                        <li><%= link_to "Sign out", destroy_user_session_path, method: :delete %></li>              <% else %>            <li><a class="nav-link" data-toggle="modal" data-target="#login-modal">Log in</a></li>            <li><a class="nav-link" data-toggle="modal" data-target="#signup-modal">Sign up</a></li>                      <% end %>      </ul>    </div>        </div>        </nav>

And this is my application.scss:

@media (max-width: 769px) {      #top{          padding-top: 40px;  		      }  }       @media (max-width: 769px) {      a:not(.navbar-brand){          padding-top: 40px;  		float: none!important;  		      }  }   

The thing is that if I type:

@media (max-width: 769px) {          a{              padding-top: 40px;      		float: none!important;      		          }      }   

It does what I want, by putting float none it works like kind of float left aligning all the a href to the left. BUT, as I said, I don't want it to do the same with the Home a href that has the class navbar-brand. That's the reason why I've tried with no success the a:not(.navbar-brand).

Is any reason why Rack::Deflater gzip is not enabled by default in Ruby on Rails?

Posted: 28 Dec 2016 02:26 AM PST

Is any reason why Rack::Deflater gzip is not enabled by default in Ruby on Rails? What are the downsides of gzip for rails, if there is any?

Start Sidekiq automatically if it is not in running state - Rails

Posted: 28 Dec 2016 03:42 AM PST

I'm using redis server and sidekiq for my cron jobs but some time sidekiq kills automatically at backend.

I want to restart sidekiq from my controller's action or automatically when it kills down without stoping my rails application server.

Please suggest me how can I manage this problem?

usage of query where in controller

Posted: 28 Dec 2016 02:36 AM PST

I want to display events of specific season and championship, but I have all the events of a championship. Where I am not right?

  resources :championships do       resources :seasons do         resources :events       end    end    class EventsController < ApplicationController    def index      @events = @championship.events.where(params[:season_id] == @season.id)    end  end    Started GET "/championships/2/seasons/2/events" for 127.0.0.1 at 2016-12-28 12:07:07 +0200  Processing by EventsController#index as HTML    Parameters: {"championship_id"=>"2", "season_id"=>"2"}    Championship Load (0.3ms)  SELECT  "championships".* FROM "championships" WHERE "championships"."id" = $1 LIMIT 1  [["id", 2]]    Season Load (0.3ms)  SELECT  "seasons".* FROM "seasons" WHERE "seasons"."id" = $1 LIMIT 1  [["id", 2]]  

RoR - Validate string on website, no error

Posted: 28 Dec 2016 02:39 AM PST

In my Ruby on Rails app I have build a function to validate if a piece of javascript is added to a certain website. When I run this code I don't get any errors in my log, but my app says:

We're sorry, but something went wrong. If you are the application owner check the logs for more information.

But when I check the logs I don't see any errors. The code I have used is the following:

def validate_installation    data  = HTTParty.get(self.website)    url = "http://www.smartnotif.com/sn.js"    if data.body.include? url      return true    else      return false    end  end  

When I run this code on my local development machine it runs fine, but when I try to runs this production machine on DigitalOcean I have this problem with the same code, no errors.

No comments:

Post a Comment