Thursday, October 27, 2016

Facebook authentification with omniauth | Fixed issues

Facebook authentification with omniauth | Fixed issues


Facebook authentification with omniauth

Posted: 27 Oct 2016 08:04 AM PDT

I'm encouter an issue with this tutorial to wreate a Facebook authetification system.

First, I had an error ActiveModel::ForbiddenAttributesError. I corrected it with coderhs answer.

Now when i loggin with facebook it works, but when i loggin with annother account, it overwrites the previous user in my table so i can't have more than 1 facebook user connected at the same time and keep informations about him

User.rb

def self.from_omniauth(auth)      where(auth.slice(provider: auth.provider, uid: auth.uid)).first_or_create.tap do |user|          user.provider ||= auth.provider          user.uid = auth.uid          user.name = auth.info.name          user.oauth_token = auth.credentials.token          user.oauth_expires_at = Time.at(auth.credentials.expires_at)          user.save!      end  

If you need some code do not hesitate to ask.

I also want to know how to get the email from the user, i tried to add

user.email = auth.email  

but it was too easy to be true

db:schema:dump on RDS with mysql. Error: Could not dump table "" because of following NoMethodError undefined method `type' for "int(11)":String

Posted: 27 Oct 2016 07:56 AM PDT

Setup:

rails: 4.2.5.1
ruby: 2.2.4p230 (2015-12-16 revision 53155) [i386-mingw32]
windows 7 environment

database.yml:

default: &default    adapter: mysql2    encoding: utf8    database: "database"    username: "name"    password: "password"    host: "host"    port: 3306     development:    adapter: mysql2    encoding: utf8    database: "database"    username: "name"    password: "password"    host: "host"    port: 3306  

I am trying to use an existing mysql database on RDS. I created a new project using
rails new "app" and then attempted to get the database schema. When I run
ruby bin\rake db:schema:dump the output in my schema.rb file is filled with the same error for every table in the database:

ActiveRecord::Schema.define() do  # Could not dump table "test" because of following NoMethodError  #   undefined method `type' for "int(11)":String  end  

I first thought that maybe it was because int(11) was a 64 bit integer, but later learned that the "11" in int(11) refers to the display size, and that it is still a 32 bit integer.

Can anyone explain why this is happening or why ruby doesn't recognize the 32 bit integer type for the primary key column.

Removal of points using Observer in Merit Rails Gem

Posted: 27 Oct 2016 07:53 AM PDT

Currently in my Observer I add points to Users based on the badges that are assigned to them.

class NewBadgeObserver    def update(changed_data)      return unless changed_data[:merit_object].is_a?(Merit::BadgesSash)        description = changed_data[:description]        user = User.where(sash_id: changed_data[:sash_id]).first      badge = changed_data[:merit_object].badge      granted_at = changed_data[:granted_at]        case badge.name      when "added-1-observation", "added-1-issue", "added-observation-at-same-location"        user.add_points(10)      when "added-10-observations", "added-10-issues", "added-10-observations-at-same-location"        user.add_points(100)      when "added-25-observations", "added-25-issues", "added-25-observations-at-same-location"        user.add_points(250)      when "added-50-observations", "added-50-issues", "added-50-observations-at-same-location", "resolved-an-issue"        user.add_points(500)      when "added-100-observations", "added-100-issues", "added-100-observations-at-same-location"        user.add_points(1000)      else        user.add_points(0)      end      end  end  

How would I go about removing these points in the Observer based on the badge being removed? Could I use the description or something similar to match against? It's not really clear from the code what happens when a badge is removed on the Observer. I guess I could do these on a controller level on the destroy method but the rules are getting really complex to remove the correct number of points.

case description    when "removed added-1-observation badge", "removed added-1-issue badge", "removed added-observation-at-same-location badge"      user.subtract_points(10)    when "removed added-10-observations badge", "removed added-10-issues badge", "removed added-10-observations-at-same-location badge"      user.subtract_points(100)    when "removed added-25-observations badge", "removed added-25-issues badge", "removed added-25-observations-at-same-location badge"      user.subtract_points(250)    when "removed added-50-observations badge", "removed added-50-issues badge", "removed added-50-observations-at-same-location badge", "removed resolved-an-issue badge"      user.subtract_points(500)    when "removed added-100-observations badge", "removed added-100-issues badge", "removed added-100-observations-at-same-location badge"      user.subtract_points(1000)    else      user.subtract_points(0)  end  

Rails: SQL query on unknown number of queries

Posted: 27 Oct 2016 07:40 AM PDT

I have a Rails search form that performs a dynamic query. That is, the user enters a search like:

(age=9) OR (gender="male" AND age=25)   

So, I don't know how many queries I will be searching by until runtime. However, the general syntax of the Rails search query is very limiting:

where("att1 LIKE ? or att2 LIKE ? or att3 LIKE ?", query_1, query_2, query_3)  

I cannot pass an array for the 'query' arguments, without Rails throwing an error.

queries = [query_1, query_2, ... , query_n]  where("att_1 LIKE ? or att_2 LIKE ? ... or att_n LIKE ?", queries)  

Error:

NoMethodError (undefined method `where' for ["a", "b", "c"]:Array)  

Attempting to splat the array yields the same error:

queries = [query_1, query_2, ... , query_n]  where("att_1 LIKE ? or att_2 LIKE ? ... or att_n LIKE ?", *queries)  

Again:

NoMethodError (undefined method `where' for ["a", "b", "c"]:Array)  

So what can I do?

Optional param in rails path

Posted: 27 Oct 2016 08:04 AM PDT

I have this conditional:

if(request.fullpath != '/')    redirect_to login_path(:redirect_url => view_context.b64_encode(request.fullpath)) unless current_user  else    redirect_to login_path unless current_user  end  

Which basically says only add the :redirect_url param if the request is not the root url. However it's meant repeating the redirect and unless code... Is it possible to make that param optional like a ternary?

HUGE model in rails? What would be the appropriate way to do it?

Posted: 27 Oct 2016 07:54 AM PDT

I'm practicing, and came up with an idea that I should create an experiment that involves building an editor that can customize a real car with all parts that a real car can have. And then allow the user to individually customize it down to the finest level of detail simply using true or false And then output it accordingly like:

<%= if @vehicle.steering_wheel_color == blue %>    show a blue steeringhweel  <% end %>    <%= if @vehicle.steering_wheel_color == red %>    show a red steeringhweel  <% end %>    <%= if @vehicle.gear_box_knob == brown_wood %>    show a brown wooden gear knob  <% end %>  

Since we're talking roughly around 500-1000 parameters(?) I'm sure that my idea of Architecture is preeeetty bad, so I'm wondering what the 'correct' or even the best way of doing it would be? considering that each variable needs to be queryable?

I've done some googling and I found one answer that advised to do one model that belongs to vehicle that houses all the booleans. But then I asked a friend and he said that would be a terrible idea.

I guess my question is, what's a good way to build a huge car-editor?

Attach dragonfly image in email rails 5

Posted: 27 Oct 2016 07:22 AM PDT

I am using dragonfly to upload images and need to send emails with those images attached. I use to display images in a web page this way and is ok,

<td><%= image_tag @some_record.some_image.thumb('400x200#').url %></td>  

I am using Action Mailer to send emails and just cant figure how to attach that image in the mailer.

Rails 5 Prawn pdf show total table values

Posted: 27 Oct 2016 07:21 AM PDT

In my view I have

<h4><%= number_to_currency @grand_total, precision: 0, unit: "EUR ", separator: "," %></h4>  

This shows a correct total for a column.

On the pdf generated by prawn I want to show the same so I tried to enter on the corresponding .rb file:

text number_to_currency(@grand_total, precision: 0, unit: "EUR ", separator: ",")  

which gives me no error but shows no value.

What is the correct syntax?

Add text dynamical on image with rails [on hold]

Posted: 27 Oct 2016 07:12 AM PDT

I need your help please… I have been tying to figure out a way to add dynamical text to an image with rails. But with no luck as of yet.

For example: How can a user on my web page add text to existing images?

Thank u all in advance.

Next & previous through @user's object?

Posted: 27 Oct 2016 07:49 AM PDT

Currently if a person clicks the link_to they're brought to the previous or next challenge.

But how can link_to work where only @user `s challenges are included?

view

<% if @challenge.previous %>    <%= link_to 'Prev', challenge_path(@challenge.previous), class: "footer-left", style: "color: white; font-style: normal;" %>  <% else %>    <%= link_to 'Home', root_url, class: "footer-left" %>  <% end %>    <% if @challenge.next %>    <%= link_to 'Next', challenge_path(@challenge.next), class: "footer-right" %>  <% else %>    <%= link_to 'Home', root_url, class: "footer-right" %>  <% end %>  

model

def next    Challenge.where("id > ?", id).first # I get nil error for... Challenge.find_by(user_id: @user.id).where("id > ?", id).first  end    def previous    Challenge.where("id < ?", id).last # I get nil error for... Challenge.find_by(user_id: @user.id).where("id > ?", id).last  end  

I know @user doesn't work in the model, but I'm just using it as an example for trying to get the User whose challenges they belong to.

Michae hartl Chapter 12 Password error

Posted: 27 Oct 2016 06:52 AM PDT

Hi guys again me with another question. I still have problems with a code and cant find a solution to my question. I followed every step till this error came. It says Expected nill to not be equal to nil. Can someone help me and explain this to me?

FAIL["test_password_resets", PasswordResetsTest, 1.7315357209881768]   test_password_resets#PasswordResetsTest (1.73s)          Expected nil to not be equal to nil.          test/integration/password_resets_test.rb:20:in `block in <class:PasswordResetsTest>'  

here is my password_reset_test.rb

require 'test_helper'    class PasswordResetsTest < ActionDispatch::IntegrationTest      def setup      ActionMailer::Base.deliveries.clear      @user = users(:michael)    end      test "password resets" do      get new_password_reset_path      assert_template 'password_resets/new'      # Invalid email      post password_resets_path, params: { password_reset: { email: "" } }      assert_not flash.empty?      assert_template 'password_resets/new'      # Valid email      post password_resets_path,           params: { password_reset: { email: @user.email } }      assert_not_equal @user.reset_digest, @user.reload.reset_digest      assert_equal 1, ActionMailer::Base.deliveries.size      assert_not flash.empty?      assert_redirected_to root_url      # Password reset form      user = assigns(:user)      # Wrong email      get edit_password_reset_path(user.reset_token, email: "")      assert_redirected_to root_url      # Inactive user      user.toggle!(:activated)      get edit_password_reset_path(user.reset_token, email: user.email)      assert_redirected_to root_url      user.toggle!(:activated)      # Right email, wrong token      get edit_password_reset_path('wrong token', email: user.email)      assert_redirected_to root_url      # Right email, right token      get edit_password_reset_path(user.reset_token, email: user.email)      assert_template 'password_resets/edit'      assert_select "input[name=email][type=hidden][value=?]", user.email      # Invalid password & confirmation      patch password_reset_path(user.reset_token),            params: { email: user.email,                      user: { password:              "foobaz",                              password_confirmation: "barquux" } }      assert_select 'div#error_explanation'      # Empty password      patch password_reset_path(user.reset_token),            params: { email: user.email,                      user: { password:              "",                              password_confirmation: "" } }      assert_select 'div#error_explanation'      # Valid password & confirmation      patch password_reset_path(user.reset_token),            params: { email: user.email,                      user: { password:              "foobaz",                              password_confirmation: "foobaz" } }      assert is_logged_in?      assert_not flash.empty?      assert_redirected_to user    end  end  

and my password_resets_controller.rb

class PasswordResetsController < ApplicationController    before_action :get_user,         only: [:edit, :update]    before_action :valid_user,       only: [:edit, :update]    before_action :check_expiration, only: [:edit, :update]    # Case (1)      def new    end      def create      @user = User.find_by(email: params[:password_reset][:email].downcase)      if @user        @user.create_reset_digest        @user.send_password_reset_email        flash[:info] = "Email sent with password reset instructions"        redirect_to root_url      else        flash.now[:danger] = "Email address not found"        render 'new'      end    end      def edit    end      def update      if params[:user][:password].empty?                  # Case (3)        @user.errors.add(:password, "can't be empty")        render 'edit'      elsif @user.update_attributes(user_params)          # Case (4)        log_in @user        @user.update_attribute(:reset_digest, nil)        flash[:success] = "Password has been reset."        redirect_to @user      else        render 'edit'                                     # Case (2)      end    end      private        def user_params        params.require(:user).permit(:password, :password_confirmation)      end        # Before filters        def get_user        @user = User.find_by(email: params[:email])      end        # Confirms a valid user.      def valid_user        unless (@user && @user.activated? &&                @user.authenticated?(:reset, params[:id]))          redirect_to root_url        end      end        # Checks expiration of reset token.      def check_expiration        if @user.password_reset_expired?          flash[:danger] = "Password reset has expired."          redirect_to new_password_reset_url        end      end  end  

thanks for the help.

masonry-brick media-item blocks tooltips

Posted: 27 Oct 2016 06:51 AM PDT

The following is in a Rails 3 application:

<i class="fa fa-hourglass-half has-tooltip info-icon-small" aria-hidden="true" data-toggle="tooltip" data-placement="auto" data-original-title="This tooltip shows up as expected."></i>  <ul class="masonry media-grid" style="margin-top: 15px;">      <li class="masonry-brick media-item">          <h3>This text shows up</h3>          <i class="fa fa-hourglass-half has-tooltip info-icon-small" aria-hidden="true" data-toggle="tooltip" data-placement="auto" data-original-title="No sign of this tooltip."></i>      </li>  </ul>  

When the page is viewed the first icon shows up with a working tooltip but the second icon's tooltip is never visible. Removing class="masonry-bick media-item" from each <li> element causes the tooltips to show up whilst, of course, making a mess of the layout.

Does anyone know why this happens, or any means of allowing the tooltips to display within the <li class="masonry-brick media-item"> elements?

An error occurred while installing pg (0.19.0), and Bundler cannot continue

Posted: 27 Oct 2016 06:49 AM PDT

Yesterday I install Ubuntu 16.04.1.

ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]

rails -v '4.2.6' create a rails project

run bundle and have an error:

Errno::EACCES: Permission denied @ rb_sysopen - /home/zeus/.rbenv/versions /2.3.1/lib/ruby/gems/2.3.0/gems/pg-0.19.0/.gemtest  An error occurred while installing pg (0.19.0), and Bundler cannot continue.  Make sure that `gem install pg -v '0.19.0'` succeeds before bundling.  

When run gem install pg -v '0.19.0'

ERROR:  While executing gem ... (Errno::EACCES)  Permission denied @ rb_sysopen - /home/zeus/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/pg-0.19.0/.gemtest  

Why in my links collection contain empty object?

Posted: 27 Oct 2016 07:14 AM PDT

Why I get collection object with nil parameters, that I didn't create advisedly?

routes.rb:

devise_for :users    root to: "posts#index"      resources :posts do      resources :comments, only: [:new, :create]        resources  :images do        resources :comments, only: [:new, :create]      end        resources  :links do        resources :comments, only: [:new, :create]      end      end  

post_controller:

 class PostsController < ApplicationController          before_filter :authenticate_user!, :only => [:new, :create]          def index          @posts = Post.all        end          def show          @post = Post.find(params[:id])        end          def new          @post = Post.new        end          def create          @post = Post.new(post_params)            respond_to do |format|            if @post.save              format.html { redirect_to @post, notice: 'Post was successfully   created.' }              format.json { render :show, status: :created, location: @post }            else              format.html { render :new }              format.json { render json: @post.errors, status: :unprocessable_entity }            end          end        end  

links_controller:

class LinksController < ApplicationController    before_action :set_link, only: [:show, :edit, :update, :destroy]      def index      @links = Link.all    end      def show    end      def new      @post = Post.find(params[:post_id])      @link = @post.links.new    end      def edit    end      def create      @post = Post.find(params[:post_id])      @link = @post.links.new(link_params)        respond_to do |format|        if @link.save          format.html { redirect_to post_path(@post,@link), notice: 'Link was successfully created.' }          format.json { render :show, status: :created, location: @link }        else          format.html { render :new }          format.json { render json: @link.errors, status: :unprocessable_entity }        end      end    end  

I get @post.links in /posts/:id, I have written on views/posts/show.html.erb:

<%= @post.links %>  

and I have got collection with empty parameters:

#<ActiveRecord::Associations::CollectionProxy   [#<Link id: nil, url: nil, created_at: nil, updated_at: nil, post_id: 6>]  

Why?

passenger-status Application groups sorting

Posted: 27 Oct 2016 06:32 AM PDT

I have a large server in AWS (32 GB ram / 8 core), our rails app has over 350 simultaneous users. We are using nginx and Passenger 4.0.57

Given I have set passenger_min_instances 50; And I have set passenger_max_pool_size 75;

When the traffic lowers Then some of the 50 process are not being used.

So when I do passenger-status I would like to see the list of processes sorted by the "last used", or by the "Memory" or by the "CPU". any sorting would be better than "PID"

Perform an INSERT in Jena Fuseki with SPARQL gem (Ruby)

Posted: 27 Oct 2016 06:34 AM PDT

So I'm developing an API in Rails and using Jena Fuseki to store triples, and right now I'm trying to perform an INSERT in a named graph. The query is correct, since I ran it on Jena and worked perfectly. However, no matter what I do when using the Rails CLI, I keep getting the same error message:

SPARQL::Client::MalformedQuery: Error 400: SPARQL Update: No 'update=' parameter  

I've created a method that takes the parameters of the object I'm trying to insert, and specified the graph where I want them.

def self.insert_taxon(uri, label, comment, subclass_of)    endpoint = SPARQL::Client.new("http://app.talkiu.com:8030/talkiutest/update")    query =       "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>        PREFIX owl: <http://www.w3.org/2002/07/owl#>        PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>        prefix gpc:<http://www.ebusiness-unibw.org/ontologies/pcs2owl/gpc/>        prefix tk: <www.web-experto.com.ar/ontology#>          INSERT DATA {          GRAPH <http://app.talkiu.com:8030/talkiutest/data/talkiu> {            <#{uri}> a owl:Class.            <#{uri}> rdfs:label '#{label}'@es .            <#{uri}> rdfs:comment '#{comment}' .            <#{uri}> rdfs:subClassOf <#{subclass_of}> .          }        }"    resultset = endpoint.query(query)  end   

As you can see, I'm using the UPDATE endpoint. Any ideas? Thanks in advance

Before action not firing when pasting in same URL with different params

Posted: 27 Oct 2016 07:27 AM PDT

I'm having a before_action :slice in my application_controller which slices some params and appends them to an object.

So let's say I visit https://myhomepage.com?param1=1&param2=2 it will slice these params and appends them to an array. When I'm staying on the page and I paste https://myhomepage.com?param1=1&param2=2 again it will not run the before action for whatever reason. Only if I press the reload button it will trigger the before action again with the new parameters.

Am I missing something here?

uninitialized constant ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::MysqlDateTime

Posted: 27 Oct 2016 05:51 AM PDT

In production environment I'm getting the below error

uninitialized constant ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::MysqlDateTime  

Someone help me to solve this issue. I have searched so many things, but I'm not able to find solution for this issue.

  • Ruby version - 2.2.0
  • Rails version - 4.2.0

Send async email about destroyed objects

Posted: 27 Oct 2016 07:12 AM PDT

In rails I have often had to send an email to someone about something that has been deleted. The issue is that when writing en asynchronously email the object has been deleted before the email is generated.

I usually only add integers and strings as parameters, just like sidekiq suggests. I thought about doing this:

mail = MyMailer.some_mail(recipient_id, deleted_object_id)  mail.delay.deliver  

But this is not recommended either: avoiding delaying methods on instances


I've also considered 2 other options, but I don't like them at all.

  1. Use acts_as_paranoid, setting a deleted_at field on the record instead of delete from db.
  2. Render the email body, save to db and send later

Any suggestions to a propper way to solve this?

Rails, Devise: Add Attributes to new created object in devise

Posted: 27 Oct 2016 05:43 AM PDT

This is my user_controller, which was generated by devise.

   def create       super     end  

I want, that all new users have the role "user". I tried this:

   def create       super do         @user.roles.create(role: "user")       end     end  

It doesn't work, but if I type in the same line of code in rails console, it does work.

What do I need to change in the controller, that all new users have the role "users"?

Internet Explorer specific styles Rails 5 Sass

Posted: 27 Oct 2016 05:34 AM PDT

Internet Explorer as usual is giving me trouble with the padding of an element and it isn't centered vertically (Edge, Firefox, Chrome, Safari are all good).

I created a ie.sass file:

.quemsomos-links-desktop-lattes          padding-top: 10px    .quemsomos-links-desktop-linkedin          padding-top: 10px  

On my assets.rb file:

Rails.application.config.assets.precompile += %w( ie.css )  

On my application.html.erb file:

<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>  <!--[if IE]>     <%= stylesheet_link_tag 'ie', media: 'all', 'data-turbolinks-track' => true %>   <![endif]-->  <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>  

According to other answers, like this one this should be enough for it to display correctly, but IE still doesn't have my specific rules.

Any ideas? Thank you very much.

rails docker-compose bundle install error

Posted: 27 Oct 2016 05:30 AM PDT

I have problem with my docker-compose on ruby on rails. when i run

docker-compose run web bundle install  

i have information that my gems installed succesfully, but when in next step i run

docker-compose up  

then i have information that my container exited with code 1. I looked on docker logs and i get information that

Could not find gem XXXXXXXXX in any list of sources(Bundler::GemNotFound)  

what is interesting i don't use this gem.

Moreover when i run bundle install outside container (on my local machine) everything works good. Where could be problem ? Please help

Bundler could not find compatible versions for gem "rack": In Gemfile:

Posted: 27 Oct 2016 05:46 AM PDT

My ruby version is 1.9.3

I am trying to configure the redmine project to my system.

I installed all the required gems. But when i start the server it showing some error.

Bundler could not find compatible versions for gem "rack":  In Gemfile:  rails (= 3.2.22) was resolved to 3.2.22, which depends on    actionpack (= 3.2.22) was resolved to 3.2.22, which depends on      rack (~> 1.4.5)    poltergeist was resolved to 1.0.0, which depends on    capybara (~> 1.1) was resolved to 1.1.4, which depends on      rack (>= 1.0.0)    rack-openid was resolved to 1.4.2, which depends on    rack (>= 1.1.0)    poltergeist was resolved to 1.0.0, which depends on    capybara (~> 1.1) was resolved to 1.1.4, which depends on      rack-test (>= 0.5.4) was resolved to 0.6.3, which depends on        rack (>= 1.0)  

I don't know what to do... My rack version is 1.6.4

miniMagick identify error in rails_admin app: Failed to manipulate with MiniMagick, maybe it is not an image?

Posted: 27 Oct 2016 05:26 AM PDT

I am using carrierwave and mini_magick gems to use images inside rails_admin. When I upload an image it fails with this error:

Failed to manipulate with MiniMagick, maybe it is not an image?   Original Error: `identify C:/Users/Zeke/AppData/Local/Temp/mini_magick20161027-21132-xdongz.png` failed with error:       identify.exe: RegistryKeyLookupFailed `CoderModulesPath' @ error/module.c/GetMagickModulePath/662.       identify.exe: no decode delegate for this image format `PNG' @ error/constitute.c/ReadImage/501.  

And this doesn't happen when I don't include the following lines in my uploader.rb

  # Process files as they are uploaded:    process resize_to_fit: [800, 600]      # Create different versions of your uploaded files:    version :thumb do      process resize_to_fill: [40, 30]    end  

I require thumbnails, and how do I do it?


Here's What I'm sure of:

  • ImageMagick has been installed and is working for sure. I am able to convert png to jpg and jpg to png, identify images...
  • identify C:/Users/Zeke/AppData/Local/Temp/mini_magick20161027-21132-xdongz.png executes successfully when run in cmd (without admin priv, if that matters)

enter image description here

  • identify -list format gives a huuuuge list that almost contains every image format I can think of. And yes, it includes JPG, JPEG, PNG and all that I need.

enter image description here

  • convert -version does include jpeg png delegates

enter image description here

What am I doing wrong?

Reference YAML keyword file for DRY controller code

Posted: 27 Oct 2016 05:07 AM PDT

I want to be able to use globally accessible symbols throughout my rails app in order to print or return a set of easily maintainable strings/sentences. I've heard of a way using YAML before but I can't remember the specifics of it's implementation or what it's called.

An example how I ideally imagine it would work:

Controller

def foo    if token.expired?      render json: { message: :token_expiry_message }    end  end    def bar    if !user.authenticate      flash[:notice] = :token_expiry_message    end  end  

Yaml file somewhere

token_expiry_message: "The user token is expired, please re-authenticate"  

This way I can DRY up my controller code and use a standard language set throughout my app by referring them from the YAML file.

Passing in an Integer with select_tag

Posted: 27 Oct 2016 05:01 AM PDT

So this is in my controller

def index      @tutor = Tutor.where(:admin => false)      @tutor = @tutor.subject_search(params[:subject_search]) if params[:subject_search].present?       @tutor = @tutor.fees_search(params[:fees_search]) if params[:fees_search].present?  end  

And this are the methods from the model

The fees_search method

def self.fees_search(amount)      @tutor ||= Tutor.where(admin: false)      @tutor.map do |tutor|        @fees = tutor.profile.fees        if @fees <= amount          #puts 'if is working'          @tutor = tutor        else          #puts 'else is working'          @tutor = nil        end        @tutor      end    end  

And this is the subject_search method

def self.subject_search(name)      @result = Subject.where("name LIKE ?" , "#{name}").take      @tutor = @result.tutors    end  

So i can do something like @tutor = Tutor.subject_search('English') in my rails console followed by @tutor.fees_search(20) and i get a result.

However when done in my index view, i receive the error comparison of Fixnum with String failed

So based on the views in the form

<%= label_tag 'fees_search', 'Fees' %>  <%= select_tag 'fees_search', options_from_collection_for_select(, :selected => params[:fees_search]), :include_blank => true, class:'form-control' %>  <%= submit_tag 'Filter', class: 'btn btn-primary btn-xs' %>  

And when i inspect in the browser, i see <option value = "10"> (and so on and so forth) which im guessing is the reason the error is coming out? If thats the case how can i set my select_tag to output integer values instead?

Or is there a more elegant solution for filtering for subjects and/or fees? Is there a need for me to post the relations?

Need simple Rails many to many association logic

Posted: 27 Oct 2016 04:26 AM PDT

I have list of products and list of categories. Also I have a mapping table 'product_categories' which tells that products comes under different category and also category has many products. Here the category list is defined by admin. Show the number of categories are fixed, but can be varied. Now i need to get the list of products which are mapped with categories

product.rb  has_many :product_categories, dependent: :destroy  has_many :categories, through: :product_categories    category.rb  has_many :product_categories  has_many :products, :through => :product_categories    product_category.rb  belongs_to :product  belongs_to :category  

I have written the code as,

ProductCategory.joins(:category).map(&:category).uniq  

Is there any way to simplify this line.

Php equivalent mcrypt_get_block_size( MCRYPT_RIJNDAEL_128 ,MCRYPT_MODE_CBC); in ruby

Posted: 27 Oct 2016 04:56 AM PDT

Need small help, can you please tell me Ruby equivalent for following code which is in php.

mcrypt_get_block_size( MCRYPT_RIJNDAEL_128 ,MCRYPT_MODE_CBC);  

I found answer for myself.

cipher = OpenSSL::Cipher.new("aes-128-cbc")  cipher.block_size  

Rails 5 rename single resource route name

Posted: 27 Oct 2016 03:45 AM PDT

I am trying to create a separate :show route, to use route globbing on the :id parameter. For this, I created a resource route without the show route and also a separate show route:

resource :test, except: [:show]  get 'test/*id', to: 'test#show', as: :test  

the problem is that I receive the error: You may have defined two routes with the same name using the:asoption, or you may be overriding a route already defined by a resource with the same naming.

If I remove as: :test it works. rails routes shows:

    tests POST   /tests(.:format)   new_test GET    /tests/new(.:format)  edit_test GET    /tests/:id/edit(.:format)       test PATCH  /tests/:id(.:format)     <-- WHY??            DELETE /tests/:id(.:format)            GET    /tests/*id(.:format)  

as you can see, resources renamed the PATCH route to :test. If I remove that route, the DELETE route is named test, and so on. How can I stop resources from using the test route name specifically? I cannot move my globbing route above the resource block obviously because then all other routes are globbed too.

What I want:

    tests POST   /tests(.:format)   new_test GET    /tests/new(.:format)  edit_test GET    /tests/:id/edit(.:format)            PATCH  /tests/:id(.:format)            DELETE /tests/:id(.:format)       test GET    /tests/*id(.:format)  

Cannot run test cases using rubymine

Posted: 27 Oct 2016 02:54 AM PDT

I am using ruby version 2.3.1 and rubymine version 8.0.1. It shows error like following when I try to run test cases

Screenshot1: Run test case using following way enter image description here

Screenshot2: Error when I run test cases enter image description here

No comments:

Post a Comment