Wednesday, March 16, 2016

Is Remote Available for DIV/SPAN in Rails 4? | Fixed issues

Is Remote Available for DIV/SPAN in Rails 4? | Fixed issues


Is Remote Available for DIV/SPAN in Rails 4?

Posted: 16 Mar 2016 06:57 AM PDT

For example, to use for the following:

#index.haml    %article-content{  :remote => true, :id => "article-#{article.id}", :class => "article-content", "data-article-id" => article.id }      #show.js.erb    var article = "#article-<%= params[:article_id] %>";  $('article').html('<%= j render ("article") %>').show();  

So far, this does not appear to work.

Timezone aware postgres query create a timeseries for minutes, hours, days

Posted: 16 Mar 2016 06:49 AM PDT

I am having a hard time to figure out how to deal with the following problem:

Our company is publishing posts to social media platforms. Those posts are stored within the database once they where successfully postet.

We want to provide a dashboard showing an overview of how many posts the user published over a time period grouped by minutes, hours and days.

I want to display the results as a time series graph.

This would work fine, but it gets very tricky once I have to support multiple time zones when I do aggregation/grouping by days. (apparently posts around midnight belong to different days depending on which time zone you are)

My current solution builds the postgres query using rails ActiveRecord. The problem I am facing is that I am struggling to deal with the timezone conversions... Also I am not particular good at postgres... The current implementation essentially looks like this (I removed irrelevant code):

Publication.select(                                                                                                                                                               %{date_trunc('#{interval}',        published_at::timestamptz at time zone interval '#{time_zone_offset}')::timestamptz as time,        count(published_at)})        .where(%(published_at BETWEEN            timestamptz '#{start_date}' AND            timestamptz '#{end_date}'))            .group("1")            .order('time').limit(LIMIT)  

For example:

I have one publication at 2016-03-15 10:19:24.219258 (Thats how it is stored inside the database therefore UTC time) I create the following query:

SELECT  date_trunc('hour',        published_at::timestamptz at time zone interval '+01:00')::timestamptz as time,        count(published_at) FROM "publications" WHERE (published_at BETWEEN            timestamptz '2016-03-15 10:00:00 +0100' AND            timestamptz '2016-03-15 12:00:00 +0100') GROUP BY 1   

;

Which results in:

          time          | count   ------------------------+-------   2016-03-15 10:00:00+01 |     1  (1 row)  

Which should be:

time: "2016-03-15 10:00:00 UTC" or "2016-03-15 11:00:00+01" ( i don't care about the time zone representation ) count: "1"

Anybody knows what I am doing wrong here?

The main problem I got stuck is that I want to be able to group/aggregate publications per day, with respect to the time zone of the user requesting the query. I don't care which time zone is returned as the front end can transform it to the user time zone.

Any feedback, help, or answer is highly appreciated. Many thanks

Rails Leaderboard Gem not working for TieRankingLeaderboard

Posted: 16 Mar 2016 06:57 AM PDT

I am using this gem for leaderboard: https://github.com/agoragames/leaderboard

When I am using the normal leaderboard, it works:

def index      highscore=Leaderboard.new('highscores')      1.upto(10) do |index|          highscore.rank_member("member_#{index}", Random.new.rand(1..100))      end  end  

However, when I am using other types of leaderboards it isn't working:

def index      highscore=TieRankingLeaderboard.new('highscores')      1.upto(10) do |index|         highscore.rank_member("member_#{index}", Random.new.rand(1..100))      end  end  

I get error: uninitialized constant ApplicationController::TieRankingLeaderboard

which means that Rails is not detecting the class.

How to make a custom form submit to the user_session_path in devise

Posted: 16 Mar 2016 06:56 AM PDT

I am trying to make a custom form login using devise. This is the code I have

<h2>login</h2>    <%= form_for(:user, :url => user_session_path) do |f| %>      <div class="field">      <%= f.label :email %><br />      <%= f.email_field :email, autofocus: true %>    </div>      <div class="field">      <%= f.label :password %>      <% if @minimum_password_length %>      <em>(<%= @minimum_password_length %> characters minimum)</em>      <% end %><br />      <%= f.password_field :password, autocomplete: "off" %>    </div>      <div class="actions">      <%= f.submit "Login" %>    </div>  <% end %>    <%= render "devise/shared/links" %>  

I generated the user model with the help of devise. I am getting the following error

undefined local variable or method `resource_name' for #<#<Class:0x007f8e54d29468>:0x007f8e49dd7500>  <%= link_to "Log in", new_session_path(resource_name) %><br />  

This is the source I followed Getting devise sign_in form into Twitter Bootstrap Modal

How can i populate database when using rspec

Posted: 16 Mar 2016 06:34 AM PDT

I'm using rspec to test my web services but when i looks in my database after each test ,i don't get anything in tables so please help me out to resolve this problem.

Here is my code:

**require 'rails_helper'    RSpec.describe "User management", :type => :request do    context "create users" do    it "creates a user by supplying facebook_token" do      headers = { "CONTENT_TYPE" => "application/json",                  "ACCEPT" => ""       }      post "/api/users", '{ "user": { "facebook_user_token":"" } }', headers      expect(response).to be_success    end  end      end**    

devise and omniauth to rails project Faraday::SSLError

Posted: 16 Mar 2016 07:02 AM PDT

I added Devise and OmniAuth to a Rails project, but instead of being redirected I get the following error:

Faraday::SSLError SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

That error comes up a lot in questions here, but I haven't found a solution that works for me yet. Does this ring a bell with anyone?

Remove underline from hyperlink - active admin

Posted: 16 Mar 2016 06:49 AM PDT

How can I remove the underline from these links?

The link is #li mail_to contact.email .

I added a div :class=> 'x' then referenciate it on the activeadmin.css.scss page but it still didn't work (thou' i added text-decoration:none)

      row("X") {          ol do            if contact.email.blank? then              li do                span :class => 'empty' do                  'Empty'                end              end            else              li mail_to contact.email            end         }  

How to find current location in ruby

Posted: 16 Mar 2016 06:21 AM PDT

I need to detect city automatically from where the user browses the site. i done by using geocoder gem.by reffering this stackoverflow answer "Rails 4 - How would I automatically detect a user's location and display it on the web app?"

Done the same steps like this, Added geocoder gem in gemfile, done bundle install and written this view code in my home page <%= request.location.city %>

i got blank output (without error), i run this code in live server

Can anyone tell me what is my mistake. Any help is appreciatable.

Ruby on Rail - Add background task to update status and expiration date

Posted: 16 Mar 2016 06:17 AM PDT

I am making a auction web app. When a ad is created, I automatically add expiration date into database.

  before_create :set_expiration_date      def set_expiration_date      self.expiration_date =  Time.now + 60.days    end   

How can I add a background task/job, so when a ad has reached its expiration date, it can change the status to false.

Is it any good gem that I could use in my case?

I have tried whenever gem and it was very cumbersome and it didn't ran in background and hard to understand.

rails Uncaught TypeError: Cannot read property 'contentDocument' of null

Posted: 16 Mar 2016 05:49 AM PDT

am making code mirror in rails but the iframe is not displaying and it caugh error. the code works fine in normal html page but fails on ruby on rails this error

new:269 Uncaught TypeError: Cannot read property 'contentDocument' of null  

and this the line it happens iframe_doc = iframe.contentDocument;

and this my whole new code

        <!DOCTYPE html>      <html lang="en">      <div class="row">      <!-- Code Editors -->    <div class="col s6">      <div class="row">        <%= form_for(@hcj) do |f| %>        <%= render 'shared/error_messages', object: f.object %>        <div class="field">          <div id="html" class="s3">            <h3>HTML</h3>              <%= f.text_area :html, placeholder: "Compose new micropost...", name: "html" %>          </div>            <div id="css" class="s3">            <h3>css</h3>            <%= f.text_area :css, placeholder: "Compose new micropost...", name: "css" %>          </div>          <div id="js" class="s3">            <h3>js</h3>            <%= f.text_area :js, placeholder: "Compose new micropost...", name: "js" %>          </div>        </div>        <%= f.submit "Post", class: "btn btn-primary" %>        <% end %>      </div>        </div>      <!-- Sandboxing -->    <h3>sandbox</h3>    <div class="col s6">      <iframe id="frameId"></iframe>    <script type="text/javascript">        var frame = window.frames.frameId;    </script>    </div>    </div>    <script>      (function () {            // Base template          var base_tpl =              "<!doctype html>\n" +              "<html>\n\t" +              "<head>\n\t\t" +              "<meta charset=\"utf-8\">\n\t\t" +              "<title>Test</title>\n\n\t\t\n\t" +              "</head>\n\t" +              "<body>\n\t\n\t" +              "</body>\n" +              "</html>";            var prepareSource = function () {              var html = html_editor.getValue(),                  css = css_editor.getValue(),                  js = js_editor.getValue(),                  src = '';                // HTML              src = base_tpl.replace('</body>', html + '</body>');                // CSS              css = '<style>' + css + '</style>';              src = src.replace('</head>', css + '</head>');                // Javascript              js = '<script>' + js + '<\/script>';              src = src.replace('</body>', js + '</body>');                return src;          };            var render = function () {              var source = prepareSource();                var iframe = document.querySelector('#output iframe'),                  iframe_doc = iframe.contentDocument;                iframe_doc.open();              iframe_doc.write(source);              iframe_doc.close();          };              // EDITORS            // CM OPTIONS          var cm_opt = {              mode: 'text/html',              gutter: true,              lineNumbers: true,          };            // HTML EDITOR          var html_box = document.querySelector('#html textarea');          var html_editor = CodeMirror.fromTextArea(html_box, cm_opt);            html_editor.on('change', function (inst, changes) {              render();          });            // CSS EDITOR          cm_opt.mode = 'css';          var css_box = document.querySelector('#css textarea');          var css_editor = CodeMirror.fromTextArea(css_box, cm_opt);            css_editor.on('change', function (inst, changes) {              render();          });            // JAVASCRIPT EDITOR          cm_opt.mode = 'javascript';          var js_box = document.querySelector('#js textarea');          var js_editor = CodeMirror.fromTextArea(js_box, cm_opt);            js_editor.on('change', function (inst, changes) {              render();          });            // SETTING CODE EDITORS INITIAL CONTENT          html_editor.setValue('<p>Hello World</p>');          css_editor.setValue('body { color: red; }');              // RENDER CALL ON PAGE LOAD          // NOT NEEDED ANYMORE, SINCE WE RELY          // ON CODEMIRROR'S onChange OPTION THAT GETS          // TRIGGERED ON setValue          // render();              // NOT SO IMPORTANT - IF YOU NEED TO DO THIS          // THEN THIS SHOULD GO TO CSS            /*            Fixing the Height of CodeMirror.            You might want to do this in CSS instead            of JS and override the styles from the main            codemirror.css          */          var cms = document.querySelectorAll('.CodeMirror');          for (var i = 0; i < cms.length; i++) {                cms[i].style.position = 'absolute';              cms[i].style.top = '30px';              cms[i].style.bottom = '0';              cms[i].style.left = '0';              cms[i].style.right = '0';              cms[i].style.height = '100%';          }          /*cms = document.querySelectorAll('.CodeMirror-scroll');          for (i = 0; i < cms.length; i++) {            cms[i].style.height = '100%';          }*/        }());  </script>  

Can I modify Devise params from within an app

Posted: 16 Mar 2016 06:28 AM PDT

I have this homework from a security class where I need to make an app using some sort of authentification system. So I decided to use ruby on rails and I got it all working with devise at the moment.

But for this home work I need an admin to be able to go into an admin page within the app and be able to modify some security options like :

  • Being able to lock people after too many login attempts
  • Complexity of user password

I can't seem to find anything on the internet for this... Is this possible ? Should I use another method ?

Thank you,

Guillaume

Categorizing on various levels Rails 4 records

Posted: 16 Mar 2016 05:35 AM PDT

I have a collection of incoming packages, that have both a certain :product and a certain supplier

To categorize it in an accordion, either by supplier or by product, I found this way that is quite DB-speed efficient:

Controller

def by_supplier      @incomings = ::Incoming::Product.all      @suppliers = @incomings.group_by(&:supplier)  end    def by_product      @incomings = ::Incoming::Product.all      @products = @incomings.group_by(&:product)  end  

Views by supplier

<% @suppliers.each_pair do |supplier, incomings| %>      <h4 class="box-title">Supplier: <%= supplier.name %></h4>      </div>          <%= render "table", data: incomings %>      </div>  <% end %>  

Views by product

<% @products.each_pair do |product, incomings| %>      <h4 class="box-title">Product: <%= product.name %></h4>      </div>          <%= render "table", data: incomings %>      </div>  <% end %>  

This gives me data like this, for instance for suppliers:

Supplier: Supplier A

  • Incoming A
  • Incoming D
  • Incoming F

Supplier: Supplier B

  • Incoming B
  • Incoming C
  • Incoming E

Supplier: Supplier C

  • Incoming H
  • Incoming J

But now I would like to categorize on 2 levels. For instance this:

Supplier: Supplier A

  • Product: Product 1

    • Incoming A
    • Incoming D
  • Product: Product 2

    • Incoming F

Supplier: Supplier B

  • Product: Product 1

    • Incoming B
  • Product: Product 3

    • Incoming C
    • Incoming E

Supplier: Supplier C

  • Product: Product 1

    • Incoming H
  • Product: Product 4

    • Incoming J

How could I achieve this, in a DB-efficient manner?

Rails: Param is nil

Posted: 16 Mar 2016 06:12 AM PDT

I'm trying to pass some params from a form to a view but all I get is param is missing or the value is empty: quotes. I've checked the database and the input is saved there but for some reason the data becomes nil somewhere along the way to the view.

I'm passing along the :quotes parameter from the view to the controller, and that should be it, shouldn't it?

quotes_controller.rb

class QuotesController < ApplicationController  def new  end    def create    @quote = Quote.new(quote_params)      @quote.save    redirect_to @quote  end    def show    @quote = Quote.find(quote_params[:id])  end    private    def quote_params      params.require(:quotes).permit(:title, :text)    end  end  

new.html.erb

<h2>Add Quote</h2>    <%= form_for :quotes, url: quotes_path do |f| %>  <p>  <%= f.label :title %><br>  <%= f.text_field :title %>  </p>    <p>  <%= f.label :text %><br>  <%= f.text_area :text %>  </p>    <p>  <%= f.submit %>  </p>  <% end %>  

show.html.erb

<h2>Saved Quotes</h2>  <p>  <strong>Title:</strong>  <%= @quote.title %>  </p>    <p>  <strong>Text:</strong>  <%= @quote.text %>  </p>  <% end %>  

I'm using the Rails Dev Box if that makes any difference.

undefined method `<<' for #<Answer::ActiveRecord_Relation:0x007fada31c7430>

Posted: 16 Mar 2016 05:40 AM PDT

Hi I create a controller Game to display a Q/A game

And I am blocked with <<, here is the code

def play      lvlup(lvl)      if lvl == 1        set_questions      else        get_questions      end      @answers = Answer.where.not(id: question.answer_id).limit(2).order("RANDOM()")      @answer ||= []      @answers << question.answer      @answers = @answers.shuffle      render 'play'    end  

I create an array and I put the related answer in the global answers I want to display 4 Max.

Why does the undefined is here?

Here is the total code

class GamesController < ApplicationController  attr_accessor :lvl      def welcome    end      def congrat    end      def play      lvlup(lvl)      if lvl == 1        set_questions      else        get_questions      end      @answers = Answer.where.not(id: question.answer_id).limit(2).order("RANDOM()")      @answer ||= []      @answers << question.answer      @answers = @answers.shuffle      render 'play'    end      def loose        @question = Question.find(params[:question])        flash.now[:alert] = "Miss..."        render 'loose'    end      def check      @lvl = params[:lvl].to_i      answer_id = params[:id].to_i      question = Question.find(params[:question])      if @lvl == lvlmax        render action: 'congrat' and return      elsif answer_id == question.answer_id        flash.now[:notice] = "Well done !"        play      else answer_id != question.answer_id        loose      end    end      private      def lvlup(value)      @lvl = 1 + value.to_i    end    def lvlmax      @lvlmax = Question.all.count    end      def set_questions      @questionsids = []      Question.all.shuffle.each do |d|        @questionsids << d.id      end      cookies[:questions] = @questionsids    end      def get_questions      @questions = cookies[:questions].split('&')    end      def questions      @questions = cookies[:questions]    end      def question      @question = Question.find(questions[lvl])    end    end  

Thank you for your help.

Providing AJAX With Rails-Generated URL

Posted: 16 Mar 2016 05:42 AM PDT

Can I provide AJAX with a Rails URL/path?

For example, what I need is url: articles/1/comments/1. Since I'm experiencing difficulties for some time now making AJAX execute this URL, I wonder if there's a way to use the Rails route I'm familiar with [comment.article, comment].

Note:

I'm loading a DIV using AJAX:

#welcome/index.haml  - @articles.each do |article|     = article.title     - article.comments.each do |comment|       %comment-content{ :id => "comment-#{ comment.id } %>", :class => "comment-content", "data-comment-id" => comment.id }  

AJAX:

  var loadComment = function() {    return $('.comment-content').each(function() {      var comment_id = $(this).data('comment-id');      return $.ajax({        url: "" ,        type: 'GET',        dataType: 'script',      });    });  };  

Rails apache pdf permissions 401

Posted: 16 Mar 2016 05:47 AM PDT

I'm going crazy trying to understand why I get a 401 (unauthorized) when trying to access pdf files. I have a project serving pdf documents and videos. Both are stored in two folders, owned by a special group (that i named ftp-users), where i can upload files via ftp but cannot be accessed directly.

drwxr-xr-x 12 accademiadipolizia ftp-users 4096 Feb 24  2015 documents/  drwxr-xr-x  2 accademiadipolizia ftp-users 4096 Aug 11  2015 videos/  

Files (documents and videos) are served with rails actions, protected with a filter that check if the user is a registered user (permissions are set with devise).

This is the action relative to pdf files

  def documents      filename = File.join([Rails.root, "private", "documents", params[:path]]) + ".pdf"      respond_to do |format|        format.pdf{          send_file filename        }      end    end  

where the "private" folder is a symbolic link to the documents folder.

and the relative route to serve the action:

resources :subjects do      get 'page', on: :member    end    get 'documents/*path', to: "subjects#documents"  

whereas the one for videos is slightly different:

resources :lessons, only: :show do      member do        get 'video'      end  

The problem is that for the videos (same similar action, same folder and files permissions, same devise filter, but a different route) everything is working fine, while for documents i always get a 401.

this is the logtrace of the server

I, [2016-03-16T13:03:45.580929 #32592]  INFO -- : Processing by SubjectsController#documents as PDF  I, [2016-03-16T13:03:45.581215 #32592]  INFO -- :   Parameters: {"path"=>"castellucci/ordinamento-della-polizia-municipale"}  I, [2016-03-16T13:03:45.583038 #32592]  INFO -- : Completed 401 Unauthorized in 1ms  

where is the problem?

EDIT:

actually the way of serving files is different: in the case of videos, the link to the video is a field of the object with the video link (so the route is a member of the object and i think devise doesn't have problems with the filter), whereas the link to the document is a direct link to the file, so in this case it's apache to serve the file... how can i find a workaround to it?

Rails routes, more optimal routing scheme in this case?

Posted: 16 Mar 2016 04:57 AM PDT

Background: view1action, view2action: I have two view types to which all the requests map to.

May I know if the routest scheme I am using below is optimal. I appreciate if someone can point to a better way.

  get '/(:a)', to: 'controller#view1action', default: { a: 'A', b: 'B' }    get '(/:a)(/:b)', to: 'controller#view1action', default: { a: 'A', b: 'B' }    get '(/:a)(/:b)/view2action/:view2action_info_source(/:page_num)', to: 'controller#view2action', default: { a: 'A', b: 'B', page_num: 0 }  

Also, I am using console to see how the urls get mapped.

> r = Rails.application.routes  > r.recognize_path('/')   => {:default=>{:a=>"A", :b=>"B"}, :controller=>"controller", :action=>"view1action"}   

Why are the defaults ':a=>"A", :b=>"B" not part of the main hash and instead as a separate hash (:default) within the main hash?

Thanks.

Rails added model attribute not filling from form

Posted: 16 Mar 2016 05:21 AM PDT

I added an attribute to a model. The form field populates, but when I submit, it doesn't input it into my DB.

The field is RoleID:

enter image description here

You can see on the next page that it does not fill the DB:

enter image description here

I have also confirmed from the DB:

+----+--------+-------------------------+----------+---------+-------+---------------------+---------------------+---------+  | id | userid | email                   | password | fname   | lname | created_at          | updated_at          | roleids |  +----+--------+-------------------------+----------+---------+-------+---------------------+---------------------+---------+  |  1 |      1 | kendallweihe@gmail.com  | test     | kendall | weihe | 2016-03-15 21:56:30 | 2016-03-15 21:56:30 |    NULL |  |  2 |      2 | kendall.weihe@gmail.com | test     | ken     | weihe | 2016-03-16 11:39:05 | 2016-03-16 11:39:05 |    NULL |  |  3 |      2 | kendall.weihe@gmail.com | test     | ken     | weihe | 2016-03-16 11:42:32 | 2016-03-16 11:42:32 |    NULL |  |  4 |      2 | kendall.weihe@gmail.com | test     | ken     | weihe | 2016-03-16 11:44:26 | 2016-03-16 11:44:26 |    NULL |  +----+--------+-------------------------+----------+---------+-------+---------------------+---------------------+---------+  

The input form looks like this:

  <div class="field">      <%= f.label :lname %><br>      <%= f.text_field :lname %>    </div>    <div class="field">      <%= f.label :roleids, "RoleID: 1 for Employee or 2 for Customer" %><br>      <%= f.number_field :roleids %>      <%debugger%>    </div>    <div class="actions">      <%= f.submit %>    </div>  

The debugger placed above confirms that the attribute exists:

#<User id: nil, userid: nil, email: nil, password: nil, fname: nil, lname: nil, created_at: nil, updated_at: nil, roleids: nil>  

The controller action looks like this:

  def create      @user = User.new(user_params)        respond_to do |format|        if @user.save          format.html { redirect_to @user, notice: 'User was successfully created.' }          format.json { render :show, status: :created, location: @user }        else          format.html { render :new }          format.json { render json: @user.errors, status: :unprocessable_entity }        end      end    end  

Icons not showing with summernote rails

Posted: 16 Mar 2016 07:07 AM PDT

enter image description here

I followed Summernote-rails official to add rich text editor in my rails project.

than in my edit.html.erb added class place_editor to my text_area

<%= f.text_area :text, class: "place_editor form-control col-md-7 col-xs-12", rows: "15j ,placeholder: "Text", required: "required"%>  

and than javascript as

<script type="text/javascript">   $(function() {        $('.place_editor').summernote();        var edit = function () {          $('.click2edit').summernote({ focus: true });        };        $("#edit").click(function () {          $('.click2edit').summernote({ focus: true });        });        $("#save").click(function () {          var aHTML = $('.click2edit').code(); //save HTML If you need(aHTML: array).          $('.click2edit').destroy();        });        // Adding Css to give border to text editor        $(".note-editor").css("border", "solid 1px #e7eaec");        });  </script>  

Everything works fine except ICONS Kindly help me out.

Unexpected float on spreadsheet import in rails

Posted: 16 Mar 2016 04:53 AM PDT

There is a field mobile_number as a string in spreadsheet in rails application but when importing a sheet, mobile_number is being stored as float. This should not happen. What can be the issue? I have already checked the format cells option in spreadsheet,it is as text. on debug

(byebug) row {"name"=>"ankita", "email"=>"ankita@gmail.com", "mobile_number"=>9650123638.0, "car_model"=>"RJ02", "date_of_purchase"=>"2015-05-03", "insurance_expiry_date "=>"2016-01-01", "warranty_expiry_date"=>"2016-01-01", "lifestyle_manager_name"=>"Amit", "lifestyle_manager_mobile_number"=>9943344532.0, "lifestyle_man ager_email"=>"amit@gmail.com"}

Problem is something like https://github.com/zdavatz/spreadsheet/issues/41

jQuery Query Builder Rails Integration

Posted: 16 Mar 2016 04:37 AM PDT

I am interested in making an advanced query builder for a rails app using the jQuery Query Builder interface: https://github.com/mistic100/jQuery-QueryBuilder

I am wondering if anyone has experience building this with rails...Is there any easy way to integrate, or pre-developed gems that help with that? This seems like a jquery plugin that could be used by many rails app developers but I was not able to find anything on Google...

Rails REST API Practices

Posted: 16 Mar 2016 05:47 AM PDT

I've come across two scenarios with regards to creating a REST API in Rails and I wonder which one is preferred. Usually if you know that you're required to have a REST API for your application at start. Does it make sense to have it in a namespace and thereby duplicating the controller logic?

I've seen examples where people have an application already and later figure they need to extend and offer a REST API. The approach to this has been to create new routes with namespacein routes.rb and controllers/api/whatever.... This still yields duplicate code though, but might be more sensible approach. The difference being a stateless machine for the REST API calls.

Can anyone elaborate on the preferred approach, thanks.

How to customize Devise Invitable

Posted: 16 Mar 2016 04:13 AM PDT

I have setup my own email invite flow in the admin view of my app. Of which ALL user must first apply for membership - and if that membership is granted (as determined by us) the admin (we) click an accept-button and an email is automatically sent out.

The accept member flow is already done, and the email goes out using SendGrid. But there is no infrastructure yet for the actual invitation token etc.

What I would like is the email to send out an invitation code which must be entered in the signup form, since our app is invite-only. Is this possible and if so how?

The devise documentation is a bit unclear to me.

How to allow users delete their own comments and not others

Posted: 16 Mar 2016 04:17 AM PDT

In my Rails App, I have a comment model ,a devise user model and a tales model. For each tales post , I have comments posted by signed-in users.The problem here is every other logged in user is able to delete the comments of other user.I want a functionality such that only the user who created the comments can delete it.

My user.rb is here

class User < ActiveRecord::Base  has_one :profile, dependent: :destroy  has_many :tales, dependent: :destroy  end  

My comment.rb is here

class Comment < ActiveRecord::Base  belongs_to :tale  end  

My tale.rb is here

class Tale < ActiveRecord::Base  belongs_to :user  has_many :comments, dependent: :destroy  belongs_to :category  end  

My routes.rb is as follows

Rails.application.routes.draw do  get 'tales/index'      devise_for :users, controllers: { registrations: "registrations" }  resources :profiles  resources :tales do    resources :comments  end  resources :categories  authenticated :user do    root "tales#index"  end    unauthenticated :user do    get "/" => "tales#index"  end  end  

My comment controller is here:

class CommentsController < ApplicationController  before_action :authenticate_user!    def create      @tale = Tale.find(params[:tale_id])      @comment = @tale.comments.create(comment_params)        redirect_to tale_path(@tale)  end    def destroy      @tale = Tale.find(params[:tale_id])      @comment = @tale.comments.find(params[:id])      @comment.destroy     end    private    def comment_params      params.require(:comment).permit(:name, :body, :tale_id)  end    end  

The excerpt from my tales/show page to add comments is here:

<div id="comments">      <h2><%= @tale.comments.count %> Comments</h2>      <%= render @tale.comments %>        <h3>Add a comment:</h3>      <%= render "comments/form" %>    </div>  </div>  

My _comment.html.erb is here

<div class="comment clearfix">  <div class="comment_content">      <p class="comment_name"><strong><%= comment.name %></strong></p>      <p class="comment_body"><%= comment.body %></p>      <p class="comment_time"><%= time_ago_in_words(comment.created_at) %>   Ago</p>  </div>      <% if user_signed_in? %>   <p><%= link_to 'Delete', [comment.tale, comment], method: :delete, data:    { confirm: 'Are you sure?' } %></p>    <% end %>      </div>  

I see no connection between user and comments and I dont the right way to do it here.Can someone guide me through this such that I can do so without using any gems .

Unknown format with wicked_pdf

Posted: 16 Mar 2016 03:48 AM PDT

I am trying to install wicked_pdf in order to generate pre-filled contracts between 2 users on my Rails application.

I feel like I have installed wicked_pdf properly, but I get an "ActionController::UnknownFormat" error.

What I did :

# Gemfile    gem 'wicked_pdf'  gem 'wkhtmltopdf-binary'  

With or without uncommenting the 'exe...' lines (one after the other), I still get the error :

# initializers/wicked_pdf.rb    WickedPdf.config = {  # Path to the wkhtmltopdf executable: This usually isn't needed if using  # one of the wkhtmltopdf-binary family of gems.  # exe_path: '/usr/local/bin/wkhtmltopdf',  #   or  # exe_path: Gem.bin_path('wkhtmltopdf-binary', 'wkhtmltopdf')    # Layout file to be used for all PDFs  # (but can be overridden in `render :pdf` calls)  # layout: 'pdf.html',  }  

My controller:

#bookings_controller.rb    class BookingsController < ApplicationController  def show    @booking = Booking.find(params[:id])    respond_to do |format|      format.html      format.pdf do        render pdf: "test_wicked_pdf"      end    end    authorize @booking # For Pundit  end  

The render HTML is working when i go to localhost:3000/bookings/135 ...

# bookings/show.html.erb    <h1>PDF test</h1>  

...but not the PDF when I comment out "# format.html" in my controller

# bookings/show.pdf.erb    <h1>PDF test</h1>  

Thanks a lot in advance

Rails, Active admin, nested form, dynamic label value - issue with the form object

Posted: 16 Mar 2016 03:31 AM PDT

I have three models:

class Request < ActiveRecord::Base    belongs_to :scenario    belongs_to :location      has_many :actions, :foreign_key => 'request_id'      accepts_nested_attributes_for :actions, :allow_destroy => true  end    class Action < ActiveRecord::Base    belongs_to :request    belongs_to :scenario_step  end    class ScenarioStep < ActiveRecord::Base    belongs_to :scenario    has_many :actions  end  

Using Active Admin I want to update information about action taken in response to a request. To do that I am using nested form:

ActiveAdmin.register Request do        permit_params :scenario_id, :location_id,                   actions_attributes: [:scenario_step_id, :description]           form(:html => {:multipart => true}) do |f|        f.inputs "Request details" do          f.input :status            panel 'Steps' do           "Text ..."          end          f.has_many :actions, heading: 'Steps to follow', allow_destroy: false, new_record: true do |ff|              ff.input :description, label: ff.object.scenario_step_id, hint: 'Text'              ff.input :scenario_step_id              end            para "Press cancel to return to the list without saving."          f.actions          end      end  end  

Everything seems to be fine except of label (or hint). As a value I want to put there related data from a table scenario_steps.

As you can see I currently try to at least print the value of scenario_step_id that should be available in the object form (ff.object.scenario_step_id) but it is not working (I have such column in actions table). On the other hand, next line: ff.input :scenario_step_id loads appropriate data into input field.

Can somebody give ma a hint what am I doing wrong?

Maintain session across multiple get requests in rspec request specs

Posted: 16 Mar 2016 04:06 AM PDT

How do I ask rspec to use/keep-alive the session used for a previous request, for the next request.

If I print the session after the first get, it is different from the session I see in the action handling blah2_path.

get blah_path, {}, headers  get blah2_path, {}, headers # use same session as blah2_path  

Change seed in devise

Posted: 16 Mar 2016 05:26 AM PDT

I have a rails projects and when I initially create the seed, the log_in page is authorizing my entry, but if I change the seed file and do

bundle exec rake db:reset   
  • which I understood it's compiling even the seed file, I receive a 401 Unauthorized message error.

seeds.rb

User.where(email: 'john_doe@yahoo.com').first_or_create! (password:'000111222')  

Am I modifying the seed in the wrong way? Should I generate anything else, apart from just changing the seed file on the plain text?

application_controller.rb

class ApplicationController < ActionController::Base  before_action :authenticate_user!, except: [:root, :forgot_password]  before_action :configure_permitted_parameters, if: :devise_controller?  # Prevent CSRF attacks by raising an exception.  # For APIs, you may want to use :null_session instead.  protect_from_forgery with: :null_session  before_action :update_headers_to_disable_caching  before_action :ie_warning  skip_before_filter  :verify_authenticity_token    ## The following are used by our Responder service classes so we can access  ## the instance variable for the current resource easily via a standard method  def resource_name   controller_name.demodulize.singularize  end    def current_resource    instance_variable_get(:"@#{resource_name}")  end    def current_resource=(val)    instance_variable_set(:"@#{resource_name}", val)  end    # Catch NotFound exceptions and handle them neatly, when URLs are mistyped or mislinked  rescue_from ActiveRecord::RecordNotFound do    render template: 'errors/error_404', status: 404  end  rescue_from CanCan::AccessDenied do    render template: 'errors/error_403', status: 403  end    # IE over HTTPS will not download if browser caching is off, so allow  browser caching when sending files  def send_file(file, opts={})    response.headers['Cache-Control'] = 'private, proxy-revalidate' # Still prevent proxy caching    response.headers['Pragma'] = 'cache'    response.headers['Expires'] = '0'    super(file, opts)  end    private    def update_headers_to_disable_caching      response.headers['Cache-Control'] = 'no-cache, no-cache="set-cookie",        no-store, private, proxy-revalidate'      response.headers['Pragma'] = 'no-cache'      response.headers['Expires'] = '-1'    end      def ie_warning      return redirect_to(ie_warning_path) if request.user_agent.to_s =~ /MSIE         [6-7]/ && request.user_agent.to_s !~ /Trident\/7.0/    end      def current_user      return unless session[:user_id]      @current_user ||= User.find(session[:user_id])    end     protected    def configure_permitted_parameters      devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:email,       :password, :remember_me) }    end   end  

SUM() immutable transactions is that cachable?

Posted: 16 Mar 2016 03:15 AM PDT

Environment:

I have a User-model and every user has_many :points_transactions. A PointsTransaction has a field with :amount. If I want to know the (points) balance of a user, I'd have to SUM("points_transactions"."amount"). While over time the amount of transactions starts to grow (the are added every minute), the SUM will take more and more time (see the simplified model code below).

Question:

What I was wondering is, since the transactions are more like a history of what happend and the past will never change, is it possible to SUM() the transactions, cache it in some way so that when a new transaction comes in, you can just use the cache + the new transaction amount.

Clear example:

User Bob (id: 1) has 5 points_transactions:

  1. amount: +5
  2. amount: +10
  3. amount: -5
  4. amount: +15
  5. amount: -10

Bob wants to know his current balance so he uses User.find(1).points_transactions.sum(:amount)

Which returns: 15.

A new transaction comes in: +5. Since the points_transactions never change, is it not possible to just take the result of the previous SUM() and add +5 to it? Like:

15 (the previous SUM result) + 5 (new transaction) = 20

Simplified model:

# models/user.rb    # Table: users  class User < ActiveRecord::Base    has_many :points_transactions      def points      points_transactions.sum(:amount)    end  end    # models/points_transaction.rb    # Table: points_transactions  # [Number] amount the points of the transaction (could be negative)  # [Int] user_id the user it is connected to  class PointsTransaction < ActiveRecord::Base    belongs_to :user  end  

I have heard it was possible on database level, but I could not find a way to actually do it. Would you guys solve this on database or on Rails level? Let me know!

Rails routing for member paths after form failing with error

Posted: 16 Mar 2016 03:24 AM PDT

Hi I am doing some experiments in Rails and have gotten stuck on a little problem with routing. Setup is like this:

Routes:

  resources :logbooks do      member do        get :entries        get 'entries/new'  => 'logbooks#new_entry'      end    end      resources :logbook_entries, only: [:create, :edit, :update, :destroy]  

The problem is happening in my form for creating a new entry entries/new
(http://localhost:3000/logbooks/1/entries/new)

This form make a POST to http://localhost:3000/logbook_entries

which will invoke the create method in LogbookEntriesController:

  def create      logbook_params = params["logbook_entry"]      logbook_id = logbook_params["logbook_id"].to_s        @logbook = Logbook.find(logbook_id)      @logbook_entry = @logbook.logbook_entries.build(create_params)      if @logbook_entry.save        flash[:info] = "Entry successfully created."        redirect_to @logbook      else          render 'logbooks/new_entry', logbook: @logbook      end    end  

My question is about this line: render 'logbooks/new_entry', logbook: @logbook when the form fails with error.

I then want to stay on same url: http://localhost:3000/logbooks/1/entries/new and keep all my values and even show the errors.

I actually got the form still and even errors but my url is like this: http://localhost:3000/logbook_entries

So if I try to POST again I acutally miss the :id of the logbook

How should the render look here? I am inside LogbookEntriesController but I want to render a page with even info about the logbook.

This is the specific question, but in general I feel quite confused about members in the routes and in which controllers the logic for these members should go. Any advice on common practise here will also be helpful.

No comments:

Post a Comment