Friday, July 22, 2016

Couldn't find Manufacturer with 'id'= (blank) | Fixed issues

Couldn't find Manufacturer with 'id'= (blank) | Fixed issues


Couldn't find Manufacturer with 'id'= (blank)

Posted: 22 Jul 2016 08:09 AM PDT

I am trying to create a web application to practise my Ruby on Rails skill. I have a few entities in my database manufacturers, models, tints, prices

manufacturers {id, name} - stores the make of the car
models {id, manufacturer_id, name} - stores the models of the car
tints {id, manufacturer_id, model_id, front, sides, rear} - stores the length of tint required
prices {id, description, price } - stores the price of the item

I created a page to generate a quotation for window tinting. The page includes drop-down menus to let user to select manufacturer, model, type of film(front), type of film(side+rear)

Below is the code for the form

<%= form_tag('/quotation/tints/generate') do %>      <%= label :manufacturer_id, 'Manufacturer' %>      <div class="field">      <%= collection_select(:tint, :manufacturer_id, Manufacturer.order(:name), :id, :name, {:prompt => "Select Manufacturer"}) %>       </div>        Model:      <div class="field">      <%= grouped_collection_select(:tint, :model_id, Manufacturer.order(:name), :models, :name, :id, :name, {:prompt => "Select Model"}) %>       </div>        <%= label :price_front, 'Front Tint' %>      <div class="field">          <%= collection_select(:price, :price_front, Price.order(:name), :id, :name, {:prompt => "Select Front Tint"}) %>       </div>        <%= label :price_rear, 'Size and Back Tint' %>      <div class="field">          <%= collection_select(:price, :price_rear, Price.order(:name), :id, :name, {:prompt => "Select Side & Rear Tint"}) %>       </div>      <div class="form-group">          <%= submit_tag 'Submit' %>      </div>  <% end %>  

When the form is submitted, it should be redirected to /quotation/tints/generate and display the value from the dropdown menu. However, I received an error, saying that Couldn't find Manufacturer with 'id'=. The code that caused the error is shown below
def generate @manufacturers = Manufacturer.find(params[:manufacturer_id]) end

Here is the parameter from the debug log

Parameters: {"utf8"=>"✓", "authenticity_token"=>"Pl2bXiRT0AoF4i0h1RCHDbuvaKJNZOkV5ULQHKxDQgZzBWWLJ2mH7ddb9akwgxbloxBIHoVaT3pcwoIGcRufpg==", "tint"=>{"manufacturer_id"=>"7", "model_id"=>"6"}, "price"=>{"price_front"=>"1", "price_rear"=>"2"}, "commit"=>"Submit"}

I can see that the id of each drop down value are shown up correctly in the parameter list. However, I coundn't able to print the value at /quotation/tints/generate nor get the name of the manufacturer or model.

Here is routes.rb
get '/quotation/tints' => 'tints#quotation', :as => 'tints_quotation' post '/quotation/tints/generate' => 'tints#generate', :as => 'generate_tints_quotation'

Tint.rb

class Tint < ApplicationRecord  has_many :manufacturers  has_many :models  belongs_to :manufacturer  belongs_to :model    validates_uniqueness_of :model_id, :scope => [:manufacturer_id] end  

Model.rb

class Model < ApplicationRecord  belongs_to :manufacturer, :dependent => :destroy  validates :name, :presence => true  validates_uniqueness_of :name, :scope => [:manufacturer_id]    before_save :capitalize_content end  

Manufacruter.rb

class Manufacturer < ApplicationRecord  has_many :models, :dependent => :destroy  validates :name, :presence => true, uniqueness: { case_sensitive: false }    before_save :capitalize_content    end  

tints.controller.rb
def quotation render 'quotation' end

def generate @manufacturers = Manufacturer.find(params[:manufacturer_id]) end

I have tried multiple ways to define it, but I am still facing the same error. Any help is greatly appreciated.

Rails login session and routing

Posted: 22 Jul 2016 07:57 AM PDT

I am new to Rails and I'm trying to make an app that with login for users, based on this code: https://www.sitepoint.com/rails-userpassword-authentication-from-scratch-part-ii/

However, the app will not let me log in, just clearing the form and showing the login page again. I suspect this has something to do with routing. In the original code, the routes.rb looks like this:

  match ':controller(/:action(/:id))(.:format)'    root :to => 'sessions#login'    match "signup", :to => "users#new"    match "login", :to => "sessions#login"    match "logout", :to => "sessions#logout"    match "home", :to => "sessions#home"    match "profile", :to => "sessions#profile"    match "setting", :to => "sessions#setting"  

This gave me a routing error for not using http methods. Modifying my own routes.rb to this:

  resources :shifts    resources :ess_members    #resources :sessions      get ':controller(/:action(/:id))(.:format)'    get 'welcome/start'    root 'welcome#start'      get "login" => "sessions#home"    get "logout" => "sessions#logout"    get "home" => "sessions#home"    get "profile" => "sessions#profile"    get "setting" => "sessions#setting"      post '/sessions/login_attempt' => 'sessions#home'  

Now I don't get any errors, but when I submit username and password to my form, I just go back to an empty login page. Putting in invalid username/password does not give an error.

Is my problem routing? And how do I fix it?

My member_controller:

class MembersController < ApplicationController    before_action :set_member, only: [:show, :edit, :update, :destroy]    before_filter :save_login_state, :only => [:new, :create]      # GET /members    # GET /members.json    def index      @members = Member.all    end      # GET /members/1    # GET /members/1.json    def show    end      # GET /members/new    def new      @member = Member.new    end      # GET /members/1/edit    def edit    end      # POST /members    # POST /members.json    def create      @member = Member.new(member_params)        respond_to do |format|        if @member.save          format.html { redirect_to @member, notice: 'Ny medlem skapades' }          format.json { render :show, status: :created, location: @member }        else          format.html { render :new }          format.json { render json: @member.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /members/1    # PATCH/PUT /members/1.json    def update      respond_to do |format|        if @member.update(member_params)          format.html { redirect_to @member, notice: 'Medlemmen uppdaterades' }          format.json { render :show, status: :ok, location: @member }        else          format.html { render :edit }          format.json { render json: @member.errors, status: :unprocessable_entity }        end      end    end      # DELETE /members/1    # DELETE /members/1.json    def destroy      @member.destroy      respond_to do |format|        format.html { redirect_to members_url, notice: 'Member was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_member        @member = Member.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def member_params        params.require(:member).permit(:memberId, :name, :password, :email, :phone, :boatType)      end    end  

My sessions_controller:

class SessionsController < ApplicationController    before_filter :authenticate_user, :except => [:index, :login, :login_attempt, :logout]  before_filter :save_login_state, :only => [:index, :login, :login_attempt]    def home      #Home Page  end    def profile      #Profile Page  end    def setting      #Setting Page  end    def login      #Login Form  end    def login_attempt  authorized_user = Member.authenticate(params[:memberId],params[:password])  if authorized_user      session[:user_id] = authorized_user.id      flash[:notice] = "Wow Welcome again, you logged in as #{authorized_user.memberId}"      redirect_to(:action => 'home')  else      flash[:notice] = "Invalid Username or Password"      flash[:color]= "invalid"      render "login"      end  end    def logout      session[:user_id] = nil      redirect_to :action => 'login'  end    end  

Thank you!

Respond_to throwing redirect error

Posted: 22 Jul 2016 07:57 AM PDT

I have the following block which takes in two values (example amount but generally more than one).

def new  # Called when campaign is approved, respond then displays table with campaign details, which when submitted is passed to create    @campaign = Campaign.find(params[:campaign_id])    @campaign.each do |value|      @applied_campaign = AppliedCampaign.new(:campaign_id => value.id, :start_date => value.start_date||Time.now, :end_date =>  value.end_date, :active => true)          respond_to do |format|        format.html # new.html.erb        format.json { render json: value }      end    end     end  

When i submit the records this block iterates through the different values I believe and then I assume looks to output these values. The problem is that I am getting the following error:

Render and/or redirect were called multiple times in this action. Please note that you may   only call render OR redirect, and at most once per action. Also note that neither redirect   nor render terminate execution of the action, so if you want to exit an action after   redirecting, you need to do something like "redirect_to(...) and return".  

Can anyone advise why this is the case and how I could generate a view with these two records displayed. Thanks!

define_method with super is causing infinite recursion

Posted: 22 Jul 2016 07:54 AM PDT

I have a form builder subclass:

class ErrorHandlingFormBuilder < ActionView::Helpers::FormBuilder  

with the following code block:

helpers.each do |name|    # We don't want to have a label for a hidden field      # ERROR: The call to super below is actually calling itself and causing infinite recursion.    #        How can I get it to call     next if name=="hidden_field"    define_method name do |field, *args|      options = args.detect {|argument| argument.is_a?(Hash)} || {}      build_shell(field, options) do        super(field,*args)      end    end  end  

The super call is calling the method it's encapsulating code block is defining! This is causing infinite recursion and Stack Level Too Deep.

What I need is for it to call the method defined by the name variable in the form builder instance itself.

I just don't know how to refer to that instance. Even using self.send instead of super still causes the recursion.

active record not retrieving data

Posted: 22 Jul 2016 08:09 AM PDT

been trying to pull products from category but its not worki. from the rails console when i enter

category = Category.where(id: 1)

will return the category but when i type

category.products

returns back

`NoMethodError: undefined method `products' for #<Category::ActiveRecord_Relation`  

but when i type

category = Category.first

then do

category.products

i get all the products belonging to that category. what am i doing wrong?

Rails Facebook Messenger Bot

Posted: 22 Jul 2016 07:52 AM PDT

This is my first question, so please let me know if I am doing something wrong. I tried to build a simple facebook messenger bot using the 'messenger-ruby' gem (https://github.com/netguru/messenger-ruby). I installed the gem successfully, but I think I don't really get how to send / receive messages.

In detail, I followed all the steps in the readme:

  1. get page access token
  2. create messenger.rb as outlined in the readme
  3. added the routes exactly as in the readme
  4. created the messenger_controller.rb as in the readme
  5. set up webhooks successfully as in the readme
  6. visited /messenger/subscribe to subscribe

This all worked so far, at https://developers.facebook.com/apps/.../messenger I see a green check under Webooks and see my page under Subscribed pages.

I did not do the "App Review for Messenger".

Now the problem: I tried to send a standard reply to every incoming message. I put the code from the readme under #components into messenger_controller.rb:

# YOUR_APP/app/controllers/messenger_controller.rb  class MessengerController < Messenger::MessengerController    def webhook    #logic here      if fb_params.first_entry.callback.message?        Messenger::Client.send(          Messenger::Request.new(            Messenger::Elements::Text.new(text: 'some text'),            fb_params.first_entry.sender_id          )        )      end      render nothing: true, status: 200    end  end  

But when one of the page admins sends a message to the page, nothing happens. I looked in the logs, but don't see the POST request I'd expect.

When use my browser to visit https:/.../messenger/webhook, I see "Invalid verify token", and in the logs it shows the following:

Started GET "/messenger/webhook" for xxx.xxx.xxx.xxx at 2016-07-22 14:39:52 +0000  Cannot render console from xxx.xxx.xxx.xxx! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255  Processing by Messenger::MessengerController#validate as HTML  Completed 200 OK in 10ms (Views: 0.3ms | ActiveRecord: 0.0ms)  

I guess that's ok, but I am not sure.

I'm sure I probably made a simple mistake, but I was reading the docs all day and couldn't find a solution. I'm not even sure what the problem is, as I'd expect to find the POST request in the logs...

Any help would really be appreciated. And please let me know how I could improve my question.

How to select values in a multiselector based on the selected values of another multiselector

Posted: 22 Jul 2016 08:04 AM PDT

I have two multiselectors as follows, the first one using the Chosen plugin:

<%= select_tag :provinces, options_for_select(DataHelper::all_provinces_captions.zip(DataHelper::all_provinces_ids)), {:multiple => true, class: 'chosen-select chzn-select', :data => {:placeholder => 'Filter Provinces/States'}, :style => "width: 100%; height: 100px;"}%>    <%= f.select :province_ids,    (DataHelper::all_provinces_captions.zip(DataHelper::all_provinces_ids)),    { include_blank: true },    {multiple: true, data: {placeholder: 'Filter Provinces/States'} }  %>  

I want to make the selected values in the :provinces selector, the same as the selected value of the :province_ids selector, on page load. Something similar to this:

$(document).ready(function() {    $("#education_plan_province_ids option:selected").each(function () {      $("#provinces option[value='"this"']").prop('selected', true);     });  });  

Except, of course, that doesn't work :D

Ruby Rails, JSON - match results if value exists

Posted: 22 Jul 2016 07:43 AM PDT

The set up is ruby on rails, in a postgres database. The table is called line_sources and a JSON column is called names. I want to return all rows where the names column contains a value called name1. I'm trying this but it fails:

LineSource.where("names ->> '%' = 'name1'")  

Perhaps jsonb can be used for that?

Rails - Event Registration Form

Posted: 22 Jul 2016 07:54 AM PDT

I am trying to create exactly the same thing explained here.

However, using

   def new        @event = Event.find params[:event_id]        @registration = @event.registration.new     end  

I get an 'undefined method':

Started GET "/events/1/registrations/new" for ::1 at 2016-07-22 13:59:08 +0200    ActiveRecord::SchemaMigration Load (0.2ms)  SELECT "schema_migrations".* FROM "schema_migrations"  Processing by RegistrationsController#new as HTML    Parameters: {"event_id"=>"1"}    Event Load (0.2ms)  SELECT  "events".* FROM "events" WHERE "events"."id" = ? LIMIT 1  [["id", 1]]  Completed 500 Internal Server Error in 30ms (ActiveRecord: 0.5ms)    NoMethodError (undefined method `registration' for #<Event:0x00000003e58bb8>  Did you mean?  registrations                 registrations=):    app/controllers/registrations_controller.rb:4:in `new'  

What am I missing?

No refresh or page reload using JS

Posted: 22 Jul 2016 07:56 AM PDT

I have an Ajax request in my Rails 4 app, but once the button is clicked it reloads the entire page. How can I keep that from happening? The page is cached so I cannot simply add a link_to or button_to. Thanks in advance.

listing_collection.js

$(document).ready(function(){    $(".listcollect").on("click", function(){        var listID = this.id;          $.ajax({            method: "GET",            url: "/listing_collections/:id/listcollect",            success: function(result) {              var arrLen = result.length              var $ul = $("<ul></ul>")              for (var i = 0; i<arrLen; i++){                  var $li = $("<li></li>");                  var $a = $("<a></a>");                  $a.attr("href", "/listings/" + listID + "/add_to_collection?listing="+listID+"$amp;listing_collection_id="+result[i]["id"]+"&amp;listing_id="+listID)                  $a.text(result[i]["name"])                  $li.append($a)                  $(this).next().append($li)              }            }.bind(this)          })      });  });  

This is the button:

<div class="btn-group listcollect-wrapper">      <button class="listcollect button btn-blue-white btn-2x dropdown-toggle" data-toggle='dropdown' type="button" id=<%= listing.id %>>Add to Listing Collection <span class="caret"></span></button>      <ul class='dropdown-menu'>        </ul>    </div>  

Rails 5 - Facebook autenticate error with omniauth-facebook

Posted: 22 Jul 2016 07:53 AM PDT

I get this error when I try use omniauth-facebook: enter image description here

Follow my code:

enter image description here

Thank you so much.

Slim rowspan aggregation with Rails data

Posted: 22 Jul 2016 08:01 AM PDT

I'm using Rails with Slim. I have this view with data (I hope that's ok to be filled with Russian): enter image description here So first column is filling with data I want to aggregate on. I want to see something like this: enter image description here But I really cannot figure out how can I do this. Here is my Slim code:

  tbody  - @managers.each do |m|    tr      td= m.region      td= m.name      ...  

And I've got hash with aggregated data like this:

{ region1: [row1, row2...],    region2: [row3, row4...]}  

But it's true problem to apply rowspan to first td only, and skip it for all other rows but first. Please help.

powder Missing helper file helpers

Posted: 22 Jul 2016 07:18 AM PDT

hello i'm trying to make powder up and it doesnt work it shows me this error Missing helper file helpers//users/adel/sites/adel_blog/app/helpers/application_helper.rb_helper.rb

enter image description here enter image description here

any ideas

How to pass GET parameters to next controller action in Ruby on Rails?

Posted: 22 Jul 2016 07:15 AM PDT

In my Rails 4.2 app I have an index action that lists all the user's invoices, filtered by search parameters in the URL:

class InvoicesController < ApplicationController      def index      @invoices = current_user.invoices.search(params)      respond_to do |format|        format.html do          @title = "Invoices"          ...        end        format.csv do          headers['Content-Disposition'] = "attachment; filename=\"#{invoices_filename}.csv\""        end        format.xls do          headers['Content-Disposition'] = "attachment; filename=\"#{invoices_filename}.xls\""        end      end    end      ...    end  

This works nicely. The user can filter his invoices by various parameters and the listed invoices adjust accordingly.

The problems start when the user wants to download these exact invoices in XLS or CSV format. I have a link for that on index.html.erb:

<%= link_to "Download invoices", invoices_path(:format => "xls") %>  

However, it downloads all the invoices, not just the ones the user filtered out previously.

Is there a way to pass the search params on to the next action or maybe a more elegant solution all together?

Thanks for any help.

Conditionally open nested view on page load using Active Scaffold

Posted: 22 Jul 2016 07:09 AM PDT

I'm using Active Scaffold and have a number of nested views configured with

config.nested.add_link(:detail)  

If I click on the link on a particular row, the page makes an AJAX request and populates the detail view beneath that row. Works great.

I would like to take a parameter in my URL that specifies that the detail view should be rendered on page load, without requiring a click, for one of the visible rows.

Is there a simple way to tell Active Scaffold to render the page and include the detail for a particular row?

How to populate parent object in nested attribute

Posted: 22 Jul 2016 07:45 AM PDT

I have two model with following association

class Article < ActiveRecord::Base    has_many :categories    accepts_nested_attributes_for :categories, reject_if: proc { |attributes| (attributes['user_id'].blank? || attributes['numbers'].blank?) }, :allow_destroy => true  end  

and

    class Category < ActiveRecord::Base        belongs_to :article          validate :mytest          def mytest          valid = self.article.phase_id != Category::STD["author"] && self.article.user_id == self.user_id  if !valid  self.article.errors.add(:base, 'Not admin user error')  end        end      end  

Here, when I debug I see that self is nil, and self.article is also nil.

And I get this error

undefined method phase_id for nil:NilClass.

How can I get article object in mytest method?

Rails: Show all posts except last post

Posted: 22 Jul 2016 06:52 AM PDT

I have created a section for my latest posts, and a section for all posts. However, my last created post gets shown twice.

In my controller, how do I show all posts except for the last post?

MainController

 def index          @post = Post.all.order('created_at DESC')          @latest_post = Post.ordered.first        end  

How to config Sails/Node App with Apache/Passenger

Posted: 22 Jul 2016 06:27 AM PDT

First of all, this is for dev purposes only. On my Mac I've got Apache running with Passenger which serve many Rails/Ruby App. An example of an Apach config for Rails would be:

<VirtualHost *:80>      ServerName example.lc      ServerAlias www.example.lc      RailsEnv development      PassengerFriendlyErrorPages on      PassengerRuby /Users/user/.rvm/gems/ruby-2.2.3/wrappers/ruby      DocumentRoot "/path/to/my/app/public"      ErrorLog "/path/to/my/app/log"      CustomLog "/path/to/my/app/log" common      ServerAdmin example@example.com          <Directory "/path/to/my/app/public">              Options Indexes FollowSymLinks              AllowOverride All              Order allow,deny              Allow from all          </Directory>  </VirtualHost>  

And on my host file I'd have 192.168.0.1 www.example.lc and that would work fine.

I'd like to do the same for a Node App based off Sails. I've tried the following:

<VirtualHost *:80>      ServerName example.lc      ServerAlias www.example.lc      NODE_ENV development      PassengerFriendlyErrorPages on      PassengerNodejs /usr/bin/node      DocumentRoot "/path/to/my/app/public"      ErrorLog "/path/to/my/app/log"      CustomLog "path/to/my/app/log" common      ServerAdmin me@example.com          <Directory "/path/to/my/app/public">              Options Indexes FollowSymLinks              AllowOverride All              Order allow,deny              Allow from all          </Directory>  </VirtualHost>  

But that doesn't work. Nor it shows any error on the log file. Any ideas?

Please note that I've also tried PassengerNodejs /Users/user/.nvm/versions/node/v4.4.7/bin/node which is the path I get when I do which node. That didn't work either.

Convert/Merge html to ruby on rails

Posted: 22 Jul 2016 06:24 AM PDT

Can someone please refer me to any tutorials that will help me merge my pre-created/ ready-made html,css,js,etc. into the Ruby on Rails. Answers are appreciated.

How Can I Change the Language Of Required Error Messages?

Posted: 22 Jul 2016 06:58 AM PDT

I created in Application with Ruby on Rails. All is in english, but when the i enter something in the fields the error message is in german. How can I change the language (english) of this message? This is my code for the view:

<%=form_for(@electricity_generation) do |f| %>  <% if @electricity_generation.errors.any? %>  <div id="error_explanation">      <h2><%= pluralize(@electricity_generation.errors.count, "error") %>          prohibited this electricity_generation from being saved:</h2>        <ul>          <% @electricity_generation.errors.full_messages.each do |message| %>          <li>              <%=m essage %>          </li>          <% end %>      </ul>  </div>  <% end %>  <section>      <h2 align="center">          Chosen Scenario:          <%=link_to @scenario_selections, scenarios_path %>      </h2>      <br>      <div class="table-row-2">          <div align="center">              <div class="field">                  <div class="table">                      <strong>Information</strong>                  </div>                  <div class="table">                      <strong>Value</strong>                  </div>                  <div class="table">                      <strong>Positive Deviation (1=100%)</strong>                  </div>                  <div class="table">                      <strong>Negative Deviation (1=100%)</strong>                  </div>                  <div class="table">                      <%=label_tag(:annual_solar_irradiation, 'Annual Solar Irradiation (kwh/m^2):') %>                  </div>                  <div class="table">                      <%=f.text_field :annual_solar_irradiation, type: "number", required: "required", placeholder: "kWh/m^2" %>                  </div>                  <div class="table">                      <%=f.text_field :asi_max, type: "number", min: "0", max: "1", step: "0.01", required: "required"%>                  </div>                  <div class="table">                      <%=f.text_field :asi_min, type: "number", min: "0", max: "1", step: "0.01", required: "required" %>                  </div>              </div>          </div>      </div>      <div align="center">          <div class="actions">              <%=f .submit %>          </div>      </div>  </section>  <% end %>  

This is how it is displayed:

enter image description here

This is the application.rb:

enter image description here

Rails assets compiling issue on AWS elasticbeanstalk

Posted: 22 Jul 2016 06:21 AM PDT

Facing an odd issue with Rails assets, and I'm not sure where the problem even lies:

I deployed my Angular Rails app onto AWS elasticbeanstalk, and the assets compiled without throwing any errors. Then when I went to the website it turns out that the application.js and application.css files were simply two lines of an angular template:

<div class="angular-flash-container" flash-message="5000"></div>  <div ui-view></div>  

All other js and css assets are not compiled or included.

All compiled images were turned a html file I had placed in "public/500.html". They were all committed as .jpg and .png images, but when they are compiled by elastic beanstalk and served their url says

<link rel="apple-touch-icon" type="image/png" href="https://cdn.site.net/images/apple-icon-57x57.png" sizes="57x57" />

but their content is a html file rather than an image.

I tried rake assets:precompile on my localmachine and everything compiles as they should. This problem only occurs on elastic beanstalk and cannot be reproduced locally. I suspect it's a problem with sprockets, but I would appreciate any pointers in how to debug this.

Here's my application.js:

//= require angular  //= require angular-resource  //= require angular-ui-router  //= require angular-smart-table  //= require angular-rails-templates  //= require checklist-model  //= require angular-datepicker  //= require velocity/velocity.min.js  //= require velocity/velocity.ui.min.js  //= require angular-velocity/angular-velocity.min.js  //= require textAngular/dist/textAngular-sanitize.min.js  //= require textAngular/dist/textAngular.min.js  //= require textAngular/dist/textAngular-rangy.min.js  //= require angular-flash-alert/dist/angular-flash.min.js  //= require angular-foundation-modal.js  //= require angular-foundation-mediaQueries.js  //= require angular-foundation-dropdownToggle.js  //= require angular-foundation-position.js  //= require angular-foundation-offcanvas.js  //= require angular-foundation-tooltip.js  //= require angular-foundation-bindHTML.js  //= require spin.js/spin.js  //= require ladda/dist/ladda.min.js  //= require angular-spinner/angular-spinner.js  //= require headroom.js/dist/headroom.min.js  //= require headroom.js/dist/angular.headroom.min.js  //= require ng-token-auth/src/ng-token-auth.coffee  //= require ngstorage/ngStorage.min.js  //= require FileSaver.js  //= require ngSmoothScroll/lib/angular-smooth-scroll.js  //= require angular-moment/angular-moment.min.js  //= require angular-elastic/elastic.js  //= require angular-validation-match/src/angular-validation-match.js  //= require angular-ui-router-title/angular-ui-router-title.js  //= require angular-loading-bar/build/loading-bar.js  //= require_tree .  //= require_tree ./templates  

application.css

 *= require_tree .   *= require_self   *= require foundation_and_overrides   *= require font-awesome   *= require textAngular/dist/textAngular.css   *= require ngSignaturePad   *= require ladda/dist/ladda-themeless.min.css  

and production.rb

# Code is not reloaded between requests.    config.cache_classes = true      # Eager load code on boot. This eager loads most of Rails and    # your application in memory, allowing both threaded web servers    # and those relying on copy on write to perform better.    # Rake tasks automatically ignore this option for performance.    config.eager_load = true      # Full error reports are disabled and caching is turned on.    config.consider_all_requests_local       = false    config.action_controller.perform_caching = true      # Enable Rack::Cache to put a simple HTTP cache in front of your application    # Add `rack-cache` to your Gemfile before enabling this.    # For large-scale production use, consider using a caching reverse proxy like    # NGINX, varnish or squid.    # config.action_dispatch.rack_cache = true      # Disable serving static files from the `/public` folder by default since    # Apache or NGINX already handles this.    # config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?    config.serve_static_files = true    config.static_cache_control = 'public, max-age=31536000'      # Compress JavaScripts and CSS.    config.assets.js_compressor = :uglifier    config.assets.css_compressor = :sass      # Do not fallback to assets pipeline if a precompiled asset is missed.    config.assets.compile = false      # Asset digests allow you to set far-future HTTP expiration dates on all assets,    # yet still be able to expire them through the digest params.    config.assets.digest = true      # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb      # Specifies the header that your server uses for sending files.    # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache    # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX      # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.    config.force_ssl = true      # Use the lowest log level to ensure availability of diagnostic information    # when problems arise.    config.log_level = :debug      # Prepend all log lines with the following tags.    # config.log_tags = [ :subdomain, :uuid ]      # Use a different logger for distributed setups.    # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)      # Use a different cache store in production.    # config.cache_store = :mem_cache_store      # Enable serving of images, stylesheets, and JavaScripts from an asset server.    config.action_controller.asset_host = ENV["CDN_DOMAIN"]      # Ignore bad email addresses and do not raise email delivery errors.    # Set this to true and configure the email server for immediate delivery to raise delivery errors.    # config.action_mailer.raise_delivery_errors = false      # Enable locale fallbacks for I18n (makes lookups for any locale fall back to    # the I18n.default_locale when a translation cannot be found).    config.i18n.fallbacks = true      # Send deprecation notices to registered listeners.    config.active_support.deprecation = :notify      #Mailer    config.action_mailer.smtp_settings = {      address:      Rails.application.secrets.smtp_address,      port:         Rails.application.secrets.smtp_port,      domain:       Rails.application.secrets.domain_name,      user_name:    Rails.application.secrets.smtp_username,      password:     Rails.application.secrets.smtp_password,      authentication: "plain",      enable_starttls_auto: true    }    # ActionMailer Config    config.action_mailer.default_url_options = { :host => Rails.application.secrets.domain_name }    config.action_mailer.delivery_method = :smtp    config.action_mailer.perform_deliveries = true    config.action_mailer.raise_delivery_errors = false      # #Local production mode Mailer    # config.action_mailer.smtp_settings = {    # address: Rails.application.secrets.smtp_address,    # port: Rails.application.secrets.smtp_port,    # domain: Rails.application.secrets.domain_name,    # user_name: Rails.application.secrets.smtp_username,    # password: Rails.application.secrets.smtp_apikey,    #   authentication:       'plain',    #   enable_starttls_auto: true  }      # # ActionMailer Config      # Use default logging formatter so that PID and timestamp are not suppressed.    config.log_formatter = ::Logger::Formatter.new      # Do not dump schema after migrations.    config.active_record.dump_schema_after_migration = false      #Mangle for angularjs    config.assets.js_compressor = Uglifier.new(mangle: false)      config.paperclip_defaults = {      storage: :s3,      s3_host_name: ENV['S3_HOST_NAME'],      s3_region: ENV['AWS_REGION'],      s3_credentials: {        bucket: ENV['S3_BUCKET_NAME'],        access_key_id: ENV['S3_ACCESS_KEY'],        secret_access_key: ENV['S3_SECRET_KEY'],      }    }  

Deleting a comment in belongs_to and has_many association

Posted: 22 Jul 2016 06:35 AM PDT

I am following Getting stated with rails simple Blog app. In the last part while deleting a comment they have used

def destroy    @article = Article.find(params[:article_id])    @comment = @article.comments.find(params[:id])    @comment.destroy    redirect_to article_path(@article)  end  

My question is why do they want to delete comment like that

@comment = @article.comments.find(params[:id])  

when

 @comment = Comment.find(params[:id])  

both returns the same @comment object. since id will be unique through out comments. why they want to take extra step in finding article. May be because first we need to check if comment belong to that article or not before deleting? or is that rails way to delete when such kind of association is setup

Failing Travis CI tests when using secret keys in rails

Posted: 22 Jul 2016 06:17 AM PDT

I am using environment variables in secrets.yml for production environment in my rails app. I am sending http post request with api key and password. I can pass my local tests in test environment by using the password. But my password can't be exposed, so how do I pass travis ci tests on github?

Disable mongoid belongs_to validation

Posted: 22 Jul 2016 06:14 AM PDT

A have two mongoid models with a simple has_many/belongs_to relationship between them.

class Lot    include Mongoid::Document    has_many :journal_items  end    class JournalItem    include Mongoid::Document    belongs_to :lot  end  

The issue is that I can't create a JournalItem without a Lot as it seems that mongoid adds a non-null validation on JournalItem.lot_id for whatever reason.

JournalItem.create!  # raises validation error "Lot can't be blank"  

How can I disable it?

I use the mongoid master with Rails 5.

OmniAuth::Strategies::OAuth2::CallbackError CSRF detected on going back from browser after successful login. Doorkeeper, devise, omniauth-oauth2

Posted: 22 Jul 2016 06:50 AM PDT

I've build an OAuth2 provider using the doorkeeper engine with devise. On my client app I'm using a custom omniauth-oauth2 -v 1.3.1 strategy. Everything works well, but after I sign in if I hit the back button on the browser I get enter image description here

I dug into the omniauth-oath2 code and it appears that there are two methods that I think are closely related to this problem, one that creates the session["omniauth.state"] from the url params:

def authorize_params          options.authorize_params[:state] = SecureRandom.hex(24)          params = options.authorize_params.merge(options_for("authorize"))          if OmniAuth.config.test_mode            @env ||= {}            @env["rack.session"] ||= {}          end          session["omniauth.state"] = params[:state]          params  end  

and one that checks this and deletes this from the session on the callback process:

def callback_phase # rubocop:disable AbcSize, CyclomaticComplexity, MethodLength, PerceivedComplexity          error = request.params["error_reason"] || request.params["error"]          if error            fail!(error, CallbackError.new(request.params["error"], request.params["error_description"] || request.params["error_reason"], request.params["error_uri"]))          elsif !options.provider_ignores_state && (request.params["state"].to_s.empty? || request.params["state"] != session.delete("omniauth.state"))            fail!(:csrf_detected, CallbackError.new(:csrf_detected, "CSRF detected"))          else            self.access_token = build_access_token            self.access_token = access_token.refresh! if access_token.expired?            super          end        rescue ::OAuth2::Error, CallbackError => e          fail!(:invalid_credentials, e)        rescue ::Timeout::Error, ::Errno::ETIMEDOUT => e          fail!(:timeout, e)        rescue ::SocketError => e          fail!(:failed_to_connect, e)    end  

It appears that somehow the first method is not called on going back from the browser. Does someone had the same problem and is there a solution to this problem without setting the :provider_ignores_state to true. Do I need to set something on the provider, I really don't get it, plus I can't seem to find this problem anywhere on the web and I highly doubt it I'm the first one that recognizes it, but I may be the first one that can't find a reasonable solution without affecting security.

Convert coffeescript function to javscript

Posted: 22 Jul 2016 05:27 AM PDT

I am following this railscast https://www.youtube.com/watch?v=ltoPZEzmtJA but I don't use coffeescript. I am trying to convert the coffeescript to javascript but I'm running into a problem.

coffeescript

jQuery ->    new AvatarCropper()    class AvatarCropper    constructor: ->      $('#cropbox').Jcrop        aspectRatio: 1        setSelect: [0, 0, 600, 600]        onSelect: @update        onChange: @update      update: (coords) =>      $("#crop_x").val coords.x      $("#crop_y").val coords.y      $("#crop_w").val coords.w      $("#crop_h").val coords.h  

js.erb file

$(document).ready(function() {      $('.crop-image').on('click', function () {      $('#cropbox').Jcrop({        aspectRatio: 1,        setSelect: [0, 0, 100, 100],        onSelect: update,        onChange: update      })    });      update: (function(_this) {      return function(coords) {        $('.user').val(coords.x);        $('.user').val(coords.y);        $('.user').val(coords.w);        return $('.user').val(coords.h);      };    })(this)      });  

I didn't understand why he decided to make a class and thought it would be more complicated to convert the whole thing. The trouble I'm having is the update function. I just plugged his coffee script for the update function into a converter and used the output. This is causing an error saying update is not defined. Where am I going wrong?

Also bonus question: what's the point of him making a class here?

Thanks!

Solr Highlighting version 1.8.24

Posted: 22 Jul 2016 05:05 AM PDT

I am quite new in Solr. I want to highlight the section where Solr finds my query. I am able to search everything.

In my model I did these things:

searchable do   text :name, :as => :name_textf, :stored => true do   |model| if not model.titles == nil              model.titles.first           else model.name            end  end    text :bodies, :stored => true  text :titles, :stored => true  

Then in my controller I searched like this

search =  Sunspot.search(TkAnalysis) do      fulltext query do        phrase_fields(tkanalysisPhraseFields(language))        fields(tkanalysisPhraseFields(language))        minimum_match [(query.split(/\W+/).count / 3.0).round, 1].max        highlight :titles, :name, :bodies      end      with :organization, $organization["sub_domain_name"]      end  

I also tried :highlight => true and :max_snippets => 3, :fragment_size => 0 also didn't help

Then for my query I don't find any highlights whatsoever even when the query is in the name

{'responseHeader'=>{  'status'=>0,  'QTime'=>31,  'params'=>{    'mm'=>'1',    'hl'=>['true',      'on'],    'indent'=>'on',    'fl'=>'* score',    'start'=>['0',      '0'],    'fq'=>'type:TkAnalysis',    'rows'=>['10',      '30'],    'version'=>'2.2',    'hl.simple.pre'=>'@@@hl@@@',    'q'=>'registre des projects',    'defType'=>'dismax',    'hl.simple.post'=>'@@@endhl@@@',    'qf'=>'name_texten^2.0 name_textf^2.0 bodies_en_text^1.5 bodies_texts^1.5 titles_en_text^1.75 titles_texts^1.75 tk_nugget_description_text^1.5 tk_nugget_document_name_text^1.0 tk_nugget_metadata_text^1.5',    'pf'=>'name_texten^2.0 name_textf^2.0 bodies_en_text^1.5 bodies_texts^1.5 titles_en_text^1.75 titles_texts^1.75 tk_nugget_description_text^1.5 tk_nugget_document_name_text^1.0 tk_nugget_metadata_text^1.5',    'hl.fl'=>'*',    'wt'=>'ruby',    'debugQuery'=>'on'}},'response'=>{'numFound'=>1,'start'=>0,'maxScore'=>0.039960045,'docs'=>[    {      'id'=>'TkAnalysis 3008571',      'guid'=>'wwwTkAnalysis3008571',      'score'=>0.039960045}]},'highlighting'=>{  'wwwTkAnalysis3008571'=>{}},'debug'=>{  'rawquerystring'=>'registre des projects',  'querystring'=>'registre des projects',  'parsedquery'=>'+((DisjunctionMaxQuery((name_textf:registre^2.0 | name_texten:registr^2.0 | titles_en_text:registre^1.75 | titles_texts:registre^1.75 | tk_nugget_document_name_text:registre | bodies_texts:registre^1.5 | tk_nugget_description_text:registre^1.5 | tk_nugget_metadata_text:registre^1.5 | bodies_en_text:registre^1.5)) DisjunctionMaxQuery((name_textf:des^2.0 | name_texten:de^2.0)) DisjunctionMaxQuery((name_textf:projects^2.0 | name_texten:project^2.0 | titles_en_text:project^1.75 | titles_texts:project^1.75 | tk_nugget_document_name_text:project | bodies_texts:project^1.5 | tk_nugget_description_text:project^1.5 | tk_nugget_metadata_text:project^1.5 | bodies_en_text:project^1.5)))~1) DisjunctionMaxQuery((name_textf:"registre des projects"^2.0 | name_texten:"registr de project"^2.0 | titles_en_text:"registre project"^1.75 | titles_texts:"registre project"^1.75 | tk_nugget_document_name_text:"registre project" | bodies_texts:"registre project"^1.5 | tk_nugget_description_text:"registre project"^1.5 | tk_nugget_metadata_text:"registre project"^1.5 | bodies_en_text:"registre project"^1.5))',  'parsedquery_toString'=>'+(((name_textf:registre^2.0 | name_texten:registr^2.0 | titles_en_text:registre^1.75 | titles_texts:registre^1.75 | tk_nugget_document_name_text:registre | bodies_texts:registre^1.5 | tk_nugget_description_text:registre^1.5 | tk_nugget_metadata_text:registre^1.5 | bodies_en_text:registre^1.5) (name_textf:des^2.0 | name_texten:de^2.0) (name_textf:projects^2.0 | name_texten:project^2.0 | titles_en_text:project^1.75 | titles_texts:project^1.75 | tk_nugget_document_name_text:project | bodies_texts:project^1.5 | tk_nugget_description_text:project^1.5 | tk_nugget_metadata_text:project^1.5 | bodies_en_text:project^1.5))~1) (name_textf:"registre des projects"^2.0 | name_texten:"registr de project"^2.0 | titles_en_text:"registre project"^1.75 | titles_texts:"registre project"^1.75 | tk_nugget_document_name_text:"registre project" | bodies_texts:"registre project"^1.5 | tk_nugget_description_text:"registre project"^1.5 | tk_nugget_metadata_text:"registre project"^1.5 | bodies_en_text:"registre project"^1.5)',  'explain'=>{    'wwwTkAnalysis3008571'=>0.039960045 = (MATCH) sum of:       0.039960045 = (MATCH) product of:  0.059940066 = (MATCH) sum of:    0.031968035 = (MATCH) max of:      0.031968035 = (MATCH) weight(name_textf:des^2.0 in 0), product of:        0.17049618 = queryWeight(name_textf:des^2.0), product of:          2.0 = boost          1.0 = idf(docFreq=1, maxDocs=2)          0.08524809 = queryNorm        0.1875 = (MATCH) fieldWeight(name_textf:des in 0), product of:          1.0 = tf(termFreq(name_textf:des)=1)          1.0 = idf(docFreq=1, maxDocs=2)          0.1875 = fieldNorm(field=name_textf, doc=0)    0.027972031 = (MATCH) max of:      0.027972031 = (MATCH) weight(tk_nugget_metadata_text:project^1.5 in 0), product of:        0.12787214 = queryWeight(tk_nugget_metadata_text:project^1.5), product of:          1.5 = boost          1.0 = idf(docFreq=1, maxDocs=2)          0.08524809 = queryNorm        0.21875 = (MATCH) fieldWeight(tk_nugget_metadata_text:project in 0), product of:          1.0 = tf(termFreq(tk_nugget_metadata_text:project)=1)          1.0 = idf(docFreq=1, maxDocs=2)          0.21875 = fieldNorm(field=tk_nugget_metadata_text, doc=0)  0.6666667 = coord(2/3)'},'QParser'=>'DisMaxQParser',  'altquerystring'=>nil,  'boostfuncs'=>nil,  'filter_queries'=>['type:TkAnalysis'],  'parsed_filter_queries'=>['type:TkAnalysis'],  'timing'=>{    'time'=>31.0,    'prepare'=>{      'time'=>0.0,      'org.apache.solr.handler.component.QueryComponent'=>{        'time'=>0.0},      'org.apache.solr.handler.component.FacetComponent'=>{        'time'=>0.0},      'org.apache.solr.handler.component.MoreLikeThisComponent'=>{        'time'=>0.0},      'org.apache.solr.handler.component.HighlightComponent'=>{        'time'=>0.0},      'org.apache.solr.handler.component.StatsComponent'=>{        'time'=>0.0},      'org.apache.solr.handler.component.DebugComponent'=>{        'time'=>0.0}},    'process'=>{      'time'=>31.0,      'org.apache.solr.handler.component.QueryComponent'=>{        'time'=>1.0},      'org.apache.solr.handler.component.FacetComponent'=>{        'time'=>0.0},      'org.apache.solr.handler.component.MoreLikeThisComponent'=>{        'time'=>0.0},      'org.apache.solr.handler.component.HighlightComponent'=>{        'time'=>27.0},      'org.apache.solr.handler.component.StatsComponent'=>{        'time'=>0.0},      'org.apache.solr.handler.component.DebugComponent'=>{        'time'=>3.0}}}}}  

Schema.xml

<dynamicField name="*_text" stored="true" type="text" multiValued="true" indexed="true"/>    <dynamicField name="*_texts" stored="true" type="text" multiValued="true" indexed="true"/>  

solconfig.xml

<highlighting>  <!-- Configure the standard fragmenter -->  <!-- This could most likely be commented out in the "default" case -->  <fragmenter name="gap" class="org.apache.solr.highlight.GapFragmenter" default="true">    <lst name="defaults">      <int name="hl.fragsize">100</int>    </lst>  </fragmenter>  <!-- A regular-expression-based fragmenter (f.i., for sentence extraction) -->  <fragmenter name="regex" class="org.apache.solr.highlight.RegexFragmenter">    <lst name="defaults">      <!-- slightly smaller fragsizes work better because of slop -->      <int name="hl.fragsize">70</int>      <!-- allow 50% slop on fragment sizes -->      <float name="hl.regex.slop">0.5</float>      <!-- a basic sentence pattern -->      <str name="hl.regex.pattern">[-\w ,/\n\"']{20,200}</str>    </lst>  </fragmenter>    <!-- Configure the standard formatter -->  <formatter name="html" class="org.apache.solr.highlight.HtmlFormatter" default="true">    <lst name="defaults">      <str name="hl.simple.pre"><![CDATA[<em>]]></str>      <str name="hl.simple.post"><![CDATA[</em>]]></str>    </lst>  </formatter>  

<!-- default values for query parameters -->    <lst name="defaults">    <str name="echoParams">explicit</str>    </lst>  

It would be great if you could shed light on why I don't get any highlighted elements. Thanks in advance!

Moped "invalid collection name"

Posted: 22 Jul 2016 04:51 AM PDT

I've recently upgraded mongoid to version 3.0.0 from 2.0 in my rails app. When performing an operation which saves an object (either existing or a new one) I'm getting Moped::Errors::OperationFailure: The operation: #<Moped::Protocol::Command saying that there is invalid collection name" .

full_collection_name for the object returns foo_development.$cmd, Mongoid.default_session.collections returns empty array but when i access the database through the mongo client, all the collections are in place.

my mongoid.yml

development: sessions: default: database: foo_development hosts: - localhost:27017

Issues with dropdown select_tag placeholder with prompt

Posted: 22 Jul 2016 06:11 AM PDT

I'm having an issue with setting a placeholder within dropdown selection form using the rails select_tag helper. Using the prompt option a placeholder exists, but this method produces a dead duplicate value in the dropdown that you can't click:

duplicate_dropdown

Here is my code:

@posts = Post.all  @categories = Post.uniq.pluck(:category)  @prompt = "Select Category"    if params[:category]     @posts = Post.where(category: params[:category])     @prompt = params[:category]  end    <%= form_tag(h_path, :method => "get") do %>     <%= select_tag 'category', options_for_select(@categories), {onchange: "this.form.submit();", prompt: @prompt} %>  <% end %>  

Any ideas or suggestions regarding making a placeholder value work nicely in this context would be greatly appreciated. By nicely I mean something like the category dropdown select example on this page: http://www.joeabercrombie.com/category/audiobooks/

How to implement Single Sign Out for Multiple Applications with Devise in Rails

Posted: 22 Jul 2016 06:04 AM PDT

There is a tutorial here on Single Sign On (SSO) for Multiple Applications with Devise, OmniAuth and Custom OAuth2 Implementation in Rails.

single Sign-on works but signing out only clears the session on current application as you can see from the destroy action below.

def destroy    session[:user_id] = nil      flash[:notice] = 'You have successfully signed out!'    redirect_to "#{CUSTOM_PROVIDER_URL}/users/sign_out"  end  

the redirect_to method doesn't work because each app make a copy the session.

How can I extend this action to support single sign-out?

No comments:

Post a Comment