Tuesday, June 21, 2016

Select records with max value of one attribute scoped to the other attribute in Rails | Fixed issues

Select records with max value of one attribute scoped to the other attribute in Rails | Fixed issues


Select records with max value of one attribute scoped to the other attribute in Rails

Posted: 21 Jun 2016 07:57 AM PDT

We have User model table:

group_id|posts|...  1       |5    |...  1       |20   |...  2       |7    |...  1       |15   |...  3       |10   |...  3       |12   |...  

And we have Group model, which has_many :users

I would like to select Group with User having the highest posts scoped to group_id.

It's important to have only one User in JOIN, because later I'm building WhereChain which filters collection based both on User and Group.

Thanks

Rails - Render and/or redirect were called multiple times in this action

Posted: 21 Jun 2016 08:05 AM PDT

I have a Rails page that lets the user select one or more records.

This is the controller action:

  def addinvtimes      @invoice = params[:invtimes][:invoice_id]      if params[:event_ids] != nil        params[:event_ids].each do |i|          newinvtime = Invtime.new(              linetype_id: 1,              invoice_id: @invoice,              event_id: i.to_i          )          if newinvtime.save            respond_to do |format|              if newinvtime.save                format.html { redirect_to invoice_path(@invoice), :notice => 'Invoice Item was successfully added.' }              else                format.html { redirect_to invoice_path(@invoice), :notice => 'ERROR.' }              end            end          end        end      end    end  

There error I get is:

Render and/or redirect were called multiple times in this action  

How can I code to not call the redirect multiple times?

When we use source in rails association

Posted: 21 Jun 2016 08:08 AM PDT

I have simple question, When we use source in our relationships ans what is meant by source.

For example

class Person < ActiveRecord::Base     belongs_to :parent, class_name: 'Person'     has_many :children, class_name: 'Person', foreign_key: :parent_id     has_many :grandchildren, class_name: 'Person', through: :children, source: :children  end  

Assume above example and guide me with simple answer

Change switch values from '0' / '1' to strings on a Rails simple_form

Posted: 21 Jun 2016 07:25 AM PDT

So I'm using Rails simple_form and this input below in order to use switches:

class SwitchInput < SimpleForm::Inputs::Base    def input      input_html_classes.unshift('fg-line')      template.content_tag(:div, class: 'toggle-switch') do        template.concat @builder.check_box(attribute_name, input_html_options)        template.concat inline_label      end    end      def inline_label      template.content_tag(:label, class: 'ts-helper') do        template.concat options[:inline_label]      end    end  end  

I'm trying to create a switch that saves the input value as a string; if it's switched to the left (default), then the value being saved is "small" and if the switch is turned to the right, then the value being saved is "large".

Right now I am saving the value as "small" / "large" via a before_save callback:

  private def convert_switch_value      if size == '0'        self.size = 'small'      else        self.size = 'large'      end        return true    end  

This is problematic because when the user returns to the form, the value being saved isn't being shown with the switch; the switch is always turned off regardless of the value being saved into the database.

Is there a way to just use simple_form to save the string values into the database AND showing the stored value when re-entering the form?

Thanks!

Create Association on Registration Devise

Posted: 21 Jun 2016 07:23 AM PDT

I currently have 3 models set up:

class User < ActiveRecord::Base      belongs_to :user_type, polymorphic: true        # Include default devise modules. Others available are:      # :confirmable, :lockable, :timeoutable and :omniauthable, :rememberable      devise :database_authenticatable, :registerable, :recoverable, :trackable, :validatable, :confirmable    end    class Teacher < ActiveRecord::Base      has_one :user, as: :user_type  end    class Student < ActiveRecord::Base      has_one :user, as: :user_type  end  

I would like to know what the best way to, upon a user signing up, create either a Student or Teacher, that is automatically associated to the User.

The Student & Teacher models have different attributes, but a User must be either one or the other.

My initial thought was to do the registration through the Student/Teacher Model, and then call devise's create method within the Student/Teacher create method, although I'm not entirely sure how to do that as well.

As an aside, one this is set up correctly, how would I go about setting different redirect paths after sign in depending on whether the user is a Student or a Teacher?

Any help is appreciated, thank you!

Rails 3 upgrade to Rails 4 url_for no longer working, need to call ActionView::RoutingUrlFor#url_for?

Posted: 21 Jun 2016 06:50 AM PDT

I'm in the process of upgrading an existing application from Rails 3 to Rails 4. I have an internal gem that needs to use the url_for gem to return URLs for a form that will be rendered.

In Rails 3 I was accomplishing this using

@template.url_for(:controller => '/foo', :action=> 'bar')

In Rails 4 this ends up using a generic method that really does nothing and actually raises an exception if passed a hash.

It appears the real logic of the old url_for has moved into ActionView::RoutingUrlFor#url_for, but I'm not sure how I can call this from outside the view now?

Sending Email Messages exposes the email addresses of every user to the recipients. How to fix?

Posted: 21 Jun 2016 07:56 AM PDT

I like to send mails such that my JobNotifier/Mailer iterates through the Subscriber's Email List and call deliver "n" times, if that could be the solution to my problem.

Unfortunately, all I have done sends Emails Messages and expose the email addresses of every user to the recipients, which is not suppose to be.

Here are my codes

create method right inside my jobs_controller.rb

def create      @job = Job.new(job_params)      if @job.save        # Deliver the Posted Job        JobNotifier.send_post_email(@job).deliver        redirect_to preview_job_path(@job)      else        render :new      end    end  

app/mailers/application_mailer.rb

class ApplicationMailer < ActionMailer::Base     default to: Proc.new { User.pluck(:email).uniq },             from: 'FarFlungJobs <no-reply@farflungjobs.com>'       layout 'mailer'    end  

app/mailers/job_notifier.rb

class JobNotifier < ApplicationMailer      def send_post_email(job)      @jobs = job      mail( :subject => 'New job posted on FarFlungJobs'          )    end    end  

test/mailers/preview/job_notifier_preview.rb

# Preview all emails at http://localhost:3000/rails/mailers/job_notifier  class JobNotifierPreview < ActionMailer::Preview      def send_post_email      user = User.all      JobNotifier.send_post_email(user)    end    end  

Tried to hop on my browser to test my Mailer using the URL shown below to preview/test my mailer:

http://localhost:3000/rails/mailers/job_notifier/send_post_email

Outcome of my test is this image below (at least if needed to help me with my problem):

Test View

Am using Rails 4.2.1

How to start Puma/Rails/Nginx on Debian after boot

Posted: 21 Jun 2016 06:42 AM PDT

Ok, I'm deploying my Rails App using Capistrano. I'm also using Puma. I've followed this tutorial to get it to work, although I'm using Debian rather then Ubuntu.

Everything works fine and I can deploy my app without issues. However if my server crashes or the server restarts, the App doesn't restart itself and the only way I got it to restart was deploying it again with the following command cap production deploy from within my App in my local machine, which we all can agree that's not ideal.

There's loads of information on the web on how to deploy a Rails App with Passenger, which I'd rather avoid to use due to lack of resources on the server part. I've also found this tutorial which seems to be a bit outdated.

Can someone please point me to an updated tutorial or give some directions on how I could get my App to start/restart who the server?

Many thanks

Better alternative to link_to :back for Cancel buttons

Posted: 21 Jun 2016 07:03 AM PDT

In my web application I have a form that is accessible from multiple screens. I'd like the Cancel button in the form to lead back to the previous page. The link_to 'Cancel', :back solution doesn't work if form is submitted before the Cancel button is pressed. In such case it simple refreshes the page, which is an expected behavior.

What is a path-independent alternative that ensures that the Cancel button always leads to the screen that the form was opened from?

how can I reference f.select tag id in rails to get value selected

Posted: 21 Jun 2016 07:20 AM PDT

Am having trouble getting the id the value from a f.select tag in rails . I need to pass the value in javascript so i can perform a calculation but the html rendered does not have the id and the only value showing is the default no matter what I choose.

in view

<%= form_for([@event, @event.reservations.new]) do |f| %>    <div class="col m6 s12">    <label for="Guests">Guests</label>    <%= f.select :guests, [["1",1], ["2",2], ["3", 3 ], ["4", 4 ], ["5", 5 ], ["6", 6 ], ["7", 7 ], ["8", 8 ], ["9", 9 ], ["10", 10 ], ["11", 11], ["12", 12 ], ["13", 13], ["14", 14], ["15+", 15 ]], id: "guests"   %>                     </div>  

in javascript

var guestSize = document.getElementById("guests").value;  

This is what is being rendered in the html

<input type="text" class="select-dropdown" readonly="true" data-activates="select-options-9586aaf6-e36f-d805-3a71-7ba42d7bbec3" value="1">  

No 'name' and 'id' showing up .

ActionController::InvalidAuthenticityToken Error in controller

Posted: 21 Jun 2016 07:04 AM PDT

So I've started getting this error after I tried to implement AJAX comments in my rails app:

ActionController::InvalidAuthenticityToken in CommentsController#create        ActionController::InvalidAuthenticityToken        def handle_unverified_request        raise ActionController::InvalidAuthenticityToken      end    end  end  

Here are all the codes from the relevant files:

comments_controller.rb

class CommentsController < ApplicationController        before_action :find_post      def create        @comment = @post.comments.build(comment_params)      @comment.user_id = current_user.id        if @comment.save        respond_to do |format|          format.html { redirect_to root_path }          format.js        end      else        flash[:alert] = "Check the comment form, something went horribly wrong."        render root_path      end    end  

Add comments form:

= form_for([post, post.comments.build], remote: true) do |f|    = f.text_field :content, placeholder: 'Add a comment...', class: "comment_content", id: "comment_content_#{post.id}"  

views/comments/create.js.erb

$('#comments_<%= @post.id %>').append("<%=j render 'comments/comment', post: @post, comment: @comment %>");  $('#comment_content_<%= @post.id %>').val('')  

comment.rb

class Comment < ActiveRecord::Base    belongs_to :user    belongs_to :post  end  

I have no idea what's causing this error as it worked fine before the introduction of AJAX. I looked up answers to similar problems on stackoverflow and added protect_from_forgery at the top of comments_controller.rb to no avail. I don't get the InvalidAuthenticityToken error alright, but instead, it gives me a different error:

NoMethodError in CommentsController#create    undefined method `id' for nil:NilClass    def create      @comment = @post.comments.build(comment_params)    @comment.user_id = current_user.id #highlighted line      if @comment.save      respond_to do |format|  

Ruby on Rails Data to Table through Joins

Posted: 21 Jun 2016 07:10 AM PDT

I have two tables, players and dailystats. I'm trying to output each column in dailystats for each player for the last 7 entries. I can loop through the player list, but have been messing with this for two days to get the daily stats for each player. Ideas?

Controller:

class MainstatsController < ApplicationController    def currenttop     @player = Player.all     @stats = Dailystat.joins(:player).select([:id, :gamesplayed]).order('id desc').limit(7)      end  end  

View:

<table>     <tr>      <th>Player</th>      <th>Games Played</th>      </tr>      <% @player.each do |player| %>      <tr>         <td><%= player.name %></td>         <td><%= player.gamesplayed %></td>      </tr>      <% end %>  </table>  

And the output of @stats in rails console.

Dailystat Load (0.5ms)  SELECT  `dailystats`.`id`,   `dailystats`.`gamesplayed`             FROM `dailystats` INNER JOIN `players` ON `players`.`id` =     `dailystats`.`player_id`  ORDER BY id desc LIMIT 7   => #<ActiveRecord::Relation [#<Dailystat id: 96, gamesplayed: 248>, #   <Dailystat id: 95, gamesplayed: 310>, #<Dailystat id: 94, gamesplayed: 345>,   #   <Dailystat id: 93, gamesplayed: 258>, #<Dailystat id: 92, gamesplayed: 359>, #    <Dailystat id: 91, gamesplayed: 331>, #<Dailystat id: 90, gamesplayed: 373>]>  

PayPal IPN - Paypal Website Standard

Posted: 21 Jun 2016 07:08 AM PDT

I've been following Railscasts on implementing Paypal Standard payments. On receiving IPN notifications, i realized i wasn't receiving Item specifics like item_name, item_number, & quantity. After some investigation, i figured i had written them wrongly in my controller as PayPal sends the variables as item_name1, item_number1, quantity1, item_name2, item_number2, quantity2 and so on

I've got the Railscasts setup. The notifications come through a controller

  PaymentNotificationsController < ApplicationController      protect_from_forgery except: [:create]       def create         PaymentNotification.create!(params: params,          item_number: params[:item_number], item_name: params[:item_name], quantity: params[:quantity]          render nothing: true       end  

In a case where an order has multiple items, it would be item_name1, item_name2, item_name3 and so on. What's the right way to name these variables, to be able to accept the paypal IPN notifications without adding a column for every extra item?

Thanks in advance!

RAILS 4: Why blank view template needed for a custom PATCH action?

Posted: 21 Jun 2016 06:29 AM PDT

In routes.rb, a custom route /db_handler is declared for doper in controller user_menus (NO model of user_menu):

  patch '/db_handler', :to => "user_menus#doper"      root :to => "user_menus#home"  

Here is home.html.erb.

<%= form_tag('/db_handler', :method => "patch") do %>         .......        <%= submit_tag 'Submit' %>  <% end  %>  

After clicking submit, there is an error:

Missing template user_menus/doper  

After creating a blank doper.html.erb, the error disappears. I don't quite understand why Rails needs to have a blank doper.html.erb for a custom patch action. What's the reasoning for that?

brew install rbenv Error: rbenv-rbenv already installed To install this version, first `brew unlink rbenv`

Posted: 21 Jun 2016 06:05 AM PDT

I am trying to install rbenv on OS X by following instruction from site link - setup ruby on macbook

when I try brew install rbenv I get below error

Error: rbenv-rbenv already installed To install this version, first 'brew unlink rbenv'  

Here is the output from brew doctor

brew doctor   Your system is ready to brew.  

I tried brew unlink rbenv on which fails with message Error: No such keg: /usr/local/Cellar/rbenv

Please suggest how this can be solved.

I have tried all solutions as listed below

brew update

brew prune

brew link rbenv

nothing really works

Rails postgres hstore: query for a specific key with any of the given values

Posted: 21 Jun 2016 05:45 AM PDT

My question is specific to rails+postgres hstore datatype.

The WHERE IN [1,2, 3] or the rails equivalent Model.where(data: [1,2,3]) works fine for regular columns, but not for hstore.

I have a hstore column(say info) and I want to query for rows which have a particular key and any one of the given values.

For example: To find all books that have a key as 'author' and value as 'ABC' in hstore column, the following query works fine:

Book.where("info @> hstore(:key, :value)", key: "author", value: "ABC")

But I need a query that returns records which have a key as 'author' and any one of values in ['ABC', 'XYZ', 'PQRS', 'DFG'].

Any suggestions?

Using devise, starting session with basic auth makes sign-out impossible

Posted: 21 Jun 2016 07:06 AM PDT

My app has an API (XML and JSON) that authorizes with basic auth and doesn't use tokens. When the user hits the API in the browser while signed out, they are prompted by the browser for username and password. If the credentials are valid they receive the appropriate JSON or XML response. At this point they are signed into the app and can visit any HTML page in addition to the API without further authorization (so they have signed into the app via the API in lieu of the normal sign in form). However, if I click the sign-out button (calls destroy_user_session_path) after signing in in this way, it does not delete the session, so user_signed_in? still returns true when it should be false and current_user still returns the account I signed in with. This causes errors elsewhere in my code and makes it so I can never really sign out.

I don't think posting much of my code will be helpful, because I do not really do anything custom with authorization. devise.rb includes:

config.http_authenticatable = true  config.skip_session_storage = []  

And in the application controller, we have:

before_action :authenticate_user!  

recaptcha.rb not found in initializer

Posted: 21 Jun 2016 06:07 AM PDT

I am following this link for captcha implementation. After including gem "recaptcha", require: "recaptcha/rails" in my Gemfile when I run bundle install at last, recaptcha.rb is not getting generated. How to fix it?

Logging GET request params in analytics?

Posted: 21 Jun 2016 05:33 AM PDT

I'm building out a video-based website in Rails 4 and want to log specific get data sent via urls.

Example: A link might send a user to /video?tags=abc, and another sends to /video?tags=123.

Is there a simple way in google analytics, or a gem to display the visits on the video page, eg:

tags   visits    abc       1    123       1  

Getting NoMethodError (undefined method `id' for nil:NilClass) on Rails Json API when trying to create new article from rails frontend site

Posted: 21 Jun 2016 06:34 AM PDT

I am getting a NoMethodError (undefined method `id' for nil:NilClass) when I'm trying to create an article from my rails frontend site. I have a rails backend site which is where I have my rails API using model serializers and then I also have a rails frontend site which connects to the rails API using activeresource.

Frontend site form:

  <form action="/users/articles" method="post">    <input name="authenticity_token" value="<%= form_authenticity_token %>" type="hidden">    <div class="form-group">      <%= label_tag 'article[title]', "name" %>      <input type="text" name="article[title]" required>    </div>    <div class="form-group">      <%= label_tag "article[content]", "E-Mail" %>      <input type="text" name= "article[content]" required>    </div>    <div class="form-group">      <%= label_tag "article[tags]", "Telephone" %>      <input type="text" name= "article[tags]" required>    </div>      <input type="submit">      <% if @errors %>      <ul class="list-unstyled">        <%@errors.each do |error|%>          <li class="has-error"><%=error%></li>        <% end -%>      </ul>    <% end %>  </form>  

Frontend /users/ articles controller:

require 'rubygems'  require 'httparty'  module Users    class ArticlesController < UsersController    # GET /articles/new    # GET /articles/new.json    def new      @article = Article.new    end      # GET /articles/1/edit    def edit      @article = Article.find(params[:id])    end      # POST /articles    # POST /articles.json    def create   @response =   HTTParty.post("http://localhost:3000/users/articles/",    :body => { :title => params[:article][:title],               :content => params[:article][:content],               :tags =>  params[:article][:tags]             }.to_json,    :headers => { 'Content-Type' => 'application/json' } )  end      # PUT /articles/1    # PUT /articles/1.json    def update      @article = Article.find(params[:id])      @article.user_id = current_user.id        respond_to do |format|        if @article.update(article_params)          format.html { redirect_to @article, notice: 'Article was successfully updated.' }          format.json { render :show, status: :ok, location: @article }        else          format.html { render :edit }          format.json { render json: @article.errors, status: :unprocessable_entity }        end      end    end  end  end  

Error in Terminal From Backend site:

Started POST "/users/articles/" for ::1 at 2016-06-21 13:26:16 +0200  Processing by Users::ArticlesController#create as HTML    Parameters: {"title"=>"frgr", "content"=>"grgrg", "tags"=>"rgr", "article"=>{"title"=>"frgr", "tags"=>"rgr", "content"=>"grgrg"}}  Completed 500 Internal Server Error in 2ms (ActiveRecord: 0.0ms)    NoMethodError (undefined method `id' for nil:NilClass):    app/controllers/users/articles_controller.rb:52:in `create'  

Article Model:

require 'active_resource'    class Article  < ActiveResource::Base    self.site = "http://localhost:3000"  end  

Routes File:

Rails.application.routes.draw do      resources :users#, only: [:show]      resources :articles      namespace :users do      resources :articles    end      # The priority is based upon order of creation: first created -> highest priority.    # See how all your routes lay out with "rake routes".      # You can have the root of your site routed with "root"     root 'welcome#index'      # Example of regular route:    #   get 'products/:id' => 'catalog#view'      # Example of named route that can be invoked with purchase_url(id: product.id)    #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase      # Example resource route (maps HTTP verbs to controller actions automatically):    #   resources :products      # Example resource route with options:    #   resources :products do    #     member do    #       get 'short'    #       post 'toggle'    #     end    #    #     collection do    #       get 'sold'    #     end    #   end      # Example resource route with sub-resources:    #   resources :products do    #     resources :comments, :sales    #     resource :seller    #   end      # Example resource route with more complex sub-resources:    #   resources :products do    #     resources :comments    #     resources :sales do    #       get 'recent', on: :collection    #     end    #   end      # Example resource route with concerns:    #   concern :toggleable do    #     post 'toggle'    #   end    #   resources :posts, concerns: :toggleable    #   resources :photos, concerns: :toggleable      # Example resource route within a namespace:    #   namespace :admin do    #     # Directs /admin/products/* to Admin::ProductsController    #     # (app/controllers/admin/products_controller.rb)    #     resources :products    #   end  end  

Infinite request on ajax

Posted: 21 Jun 2016 06:40 AM PDT

I am working on an app where user can heart(like) stories. I am trying to implement it with ajax. I have a StoriesController with the heart action. Whenever the heart(like) is clicked, I have responded with heart.js.erb and send a post request. I am working on to update the number of hearts when the user clicks the heart link. But what I am getting is infinite requests via ajax. Below is the snippet of heart action.

# Give your heart to someone    def heart      respond_to do |format|        format.js        format.html      end    end  

And ajax request is:

$('#heart-story-<%= j params[:id]%>').html('<%= @hearts %>')  $.post("/stories/<%= j params[:id]%>/heart", <%= j params[:id] %>)  console.log("<%= j params[:id] %>")  

What is the probable reason that I am getting infinite request? The route is:

#Stories  resources :stories, only: [:show, :create, :destroy] do  member do    get :heart, :unheart    post :heart, :unheart  end  # Comments  resources :comments, only: [:index, :new, :create, :destroy]  end  

Remove boolean and add list in ruby on rails

Posted: 21 Jun 2016 05:34 AM PDT

I would like to modify gender field, Initially i have declared gender field as boolean true or false. but now i want it to be changed as list (Male, Female, Other).

class AddExtraFieldsToUser < ActiveRecord::Migration    def change      add_column :users, :phone_number, :string      add_column :users, :date_of_birth, :datetime      add_column :users, :gender, :boolean, default: false      add_column :users, :live_in, :string      add_column :users, :description, :text      end  end  

Can i modify as following.... please let me know the correct way...

i thought of doing rails g migration RemovegenderFromUsers gender:boolean then rake db:migrate followed by creating new one

rails g migration AddGenderToUsers gender:select  

user.rb

GENDER_TYPES = ["Male", "Female", "Other"]  

html

<%= f.select :gender,  User::GENDER_TYPES %>  

Is above mentioned process correct or any other way ?

Native Extension Error After Installing Git & Heroku

Posted: 21 Jun 2016 04:59 AM PDT

I've been searching for a solution since yesterday and everything I've tried leads to a dead end.

New to RoR and walking through tutorials. Everything was working fine, until I started setting up GIT and Heroku. I had to install jruby_windows and heroku-toolbelt, and I believe this botched things up.

Now when I run bundle install I receive the following output errors

\BookReview>bundle install  Fetching gem metadata from https://rubygems.org/...........  Fetching version metadata from https://rubygems.org/...  Fetching dependency metadata from https://rubygems.org/..  Resolving dependencies........  Using rake 11.2.2  Using i18n 0.7.0  Using json 1.8.3  Using minitest 5.9.0  Using thread_safe 0.3.5  Using builder 3.2.2  Using erubis 2.7.0  Using nokogiri 1.6.8  Using rack 1.6.4  Using mime-types-data 3.2016.0521  Using arel 6.0.3  Using execjs 2.7.0  Using bcrypt 3.1.11  Using bcrypt-ruby 3.0.1  Using debug_inspector 0.0.2  Using sass 3.4.22  Using bundler 1.12.5  Installing byebug 9.0.5 with native extensions  C:/jruby-9.0.0.0/lib/ruby/stdlib/rubygems/ext/ext_conf_builder.rb:39: warning: Tempfile#unlink or delete called on open file; ignoring    Gem::Ext::BuildError: ERROR: Failed to build gem native extension.        C:/jruby-9.0.0.0/bin/jruby.exe -r ./siteconf20160621-9244-az7xx.rb extconf.rb  NotImplementedError: C extensions are not supported      <top> at C:/jruby-9.0.0.0/lib/ruby/stdlib/mkmf.rb:1    require at org/jruby/RubyKernel.java:940     (root) at C:/jruby-9.0.0.0/lib/ruby/stdlib/rubygems/core_ext/kernel_require.rb:1      <top> at extconf.rb:1    extconf failed, exit code 1    Gem files will remain installed in C:/jruby-9.0.0.0/lib/ruby/gems/shared/gems/byebug-9.0.5 for inspection.  Results logged to C:/jruby-9.0.0.0/lib/ruby/gems/shared/extensions/universal-java-1.8/2.2.0/byebug-9.0.5/gem_make.out  Using coffee-script-source 1.10.0  Using thor 0.19.1  Using concurrent-ruby 1.0.2  Using orm_adapter 0.5.0  Using multi_json 1.12.1  Using mimemagic 0.3.0  Installing mysql2 0.4.4 with native extensions  C:/jruby-9.0.0.0/lib/ruby/stdlib/rubygems/ext/ext_conf_builder.rb:39: warning: Tempfile#unlink or delete called on open file; ignoring    Gem::Ext::BuildError: ERROR: Failed to build gem native extension.        C:/jruby-9.0.0.0/bin/jruby.exe -r ./siteconf20160621-9244-13ylh37.rb extconf.rb  NotImplementedError: C extensions are not supported      <top> at C:/jruby-9.0.0.0/lib/ruby/stdlib/mkmf.rb:1    require at org/jruby/RubyKernel.java:940     (root) at C:/jruby-9.0.0.0/lib/ruby/stdlib/rubygems/core_ext/kernel_require.rb:1      <top> at extconf.rb:2    extconf failed, exit code 1    Gem files will remain installed in C:/jruby-9.0.0.0/lib/ruby/gems/shared/gems/mysql2-0.4.4 for inspection.  Results logged to C:/jruby-9.0.0.0/lib/ruby/gems/shared/extensions/universal-java-1.8/2.2.0/mysql2-0.4.4/gem_make.out  Using raty_ratings 1.2.0  Using tilt 2.0.5  Using rdoc 4.2.2  Using tzinfo 1.2.2  Using loofah 2.0.3  Using rack-test 0.6.3  Using warden 1.2.6  Using mime-types 3.1  Using autoprefixer-rails 6.3.6.2  Using uglifier 3.0.0  Installing binding_of_caller 0.7.2 with native extensions  C:/jruby-9.0.0.0/lib/ruby/stdlib/rubygems/ext/ext_conf_builder.rb:39: warning: Tempfile#unlink or delete called on open file; ignoring    Gem::Ext::BuildError: ERROR: Failed to build gem native extension.        C:/jruby-9.0.0.0/bin/jruby.exe -r ./siteconf20160621-9244-wni27b.rb extconf.rb  NotImplementedError: C extensions are not supported      <top> at C:/jruby-9.0.0.0/lib/ruby/stdlib/mkmf.rb:1    require at org/jruby/RubyKernel.java:940     (root) at C:/jruby-9.0.0.0/lib/ruby/stdlib/rubygems/core_ext/kernel_require.rb:1      <top> at extconf.rb:19    extconf failed, exit code 1    Gem files will remain installed in C:/jruby-9.0.0.0/lib/ruby/gems/shared/gems/binding_of_caller-0.7.2 for inspection.  Results logged to C:/jruby-9.0.0.0/lib/ruby/gems/shared/extensions/universal-java-1.8/2.2.0/binding_of_caller-0.7.2/gem_make.out  An error occurred while installing byebug (9.0.5), and Bundler cannot continue.  Make sure that `gem install byebug -v '9.0.5'` succeeds before bundling.  

rails db schema sql format TypeError: no implicit conversion of nil into String

Posted: 21 Jun 2016 04:13 AM PDT

After I added this line to my application.rb file

config.active_record.schema_format = :sql  

I start getting this error when I am running migration

bundle exec rake db:migrate --trace        ** Invoke db:migrate (first_time)  ** Invoke environment (first_time)  ** Execute environment  ** Invoke db:load_config (first_time)  ** Execute db:load_config  ** Execute db:migrate  ** Invoke db:_dump (first_time)  ** Execute db:_dump  ** Invoke db:structure:dump (first_time)  ** Invoke environment  ** Invoke db:load_config  ** Execute db:structure:dump  I, [2016-06-21T08:09:14.083751 #51538]  INFO -- : [Rollbar] Scheduling item  I, [2016-06-21T08:09:14.102300 #51538]  INFO -- : [Rollbar] Details: https://rollbar.com/instance/uuid?uuid=fgfffgf (only available if report was successful)  rake aborted!  TypeError: no implicit conversion of nil into String  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-5.0.0.rc1/lib/active_record/tasks/postgresql_database_tasks.rb:99:in `system'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-5.0.0.rc1/lib/active_record/tasks/postgresql_database_tasks.rb:99:in `run_cmd'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-5.0.0.rc1/lib/active_record/tasks/postgresql_database_tasks.rb:64:in `structure_dump'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-5.0.0.rc1/lib/active_record/tasks/database_tasks.rb:207:in `structure_dump'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-5.0.0.rc1/lib/active_record/railties/databases.rake:292:in `block (3 levels) in <top (required)>'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:248:in `block in execute'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:243:in `each'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:243:in `execute'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:187:in `block in invoke_with_call_chain'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:180:in `invoke_with_call_chain'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:173:in `invoke'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-5.0.0.rc1/lib/active_record/railties/databases.rake:67:in `block (2 levels) in <top (required)>'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:248:in `block in execute'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:243:in `each'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:243:in `execute'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:187:in `block in invoke_with_call_chain'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:180:in `invoke_with_call_chain'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:173:in `invoke'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-5.0.0.rc1/lib/active_record/railties/databases.rake:59:in `block (2 levels) in <top (required)>'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:248:in `block in execute'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:243:in `each'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:243:in `execute'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:187:in `block in invoke_with_call_chain'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:180:in `invoke_with_call_chain'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/task.rb:173:in `invoke'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:152:in `invoke_task'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:108:in `block (2 levels) in top_level'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:108:in `each'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:108:in `block in top_level'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:117:in `run_with_threads'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:102:in `top_level'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:80:in `block in run'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:178:in `standard_exception_handling'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/lib/rake/application.rb:77:in `run'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rake-11.2.2/exe/rake:27:in `<top (required)>'  /Users/atrthur/.rbenv/versions/2.3.1/bin/rake:23:in `load'  /Users/atrthur/.rbenv/versions/2.3.1/bin/rake:23:in `<top (required)>'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/cli/exec.rb:63:in `load'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/cli/exec.rb:63:in `kernel_load'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/cli/exec.rb:24:in `run'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/cli.rb:304:in `exec'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor.rb:359:in `dispatch'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor/base.rb:440:in `start'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/cli.rb:11:in `start'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/exe/bundle:27:in `block in <top (required)>'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/friendly_errors.rb:98:in `with_friendly_errors'  /Users/atrthur/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/exe/bundle:19:in `<top (required)>'  /Users/atrthur/.rbenv/versions/2.3.1/bin/bundle:23:in `load'  /Users/atrthur/.rbenv/versions/2.3.1/bin/bundle:23:in `<main>'  Tasks: TOP => db:structure:dump  

This error is disapiars if I remove that line from application.rb

Also one of my tables uses JSONB data field, not sure if this problem releated to this.

How to fix this?

Ruby on Rails – admin comment approval on a blog

Posted: 21 Jun 2016 06:10 AM PDT

I am creating a blog that has pins and comments. I am wondering how to create a system whereby the admin can approve comments on blogs before users can view them.

First I tried adding a boolean field called pinreview to my comments model:

comment.rb
class Comment < ActiveRecord::Base    belongs_to :pin      scope :approved, ->{      where(:pinreview => false)    }    scope :pending, -> {      where(:pinreview => true)    }      scope :newest, -> {      order("created_at desc")    }  end  
class CommentsController < ApplicationController    def create      @pin = Pin.find(params[:pin_id])      @comment = @pin.comments.create(params[:comment].permit(:name, :body))        redirect_to pin_path(@pin)    end      def destroy      @pin = Pin.find(params[:pin_id])      @comment = @pin.comments.find(params[:id])      @comment.destroy        redirect_to pin_path(@pin)    end  end  

I have defined the user types through enums:

class User < ActiveRecord::Base      devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable      enum access_level: [:guest, :admin]    has_many :pins      def admin      admin?    end      def guest      guest?    end    end  

And in my view I have been trying things like this:

pins/show.html.erb
...      - if current_user && current_user.admin? ? @pin.comments = Comment.all : @pin.comments = Comment.where(:approved => false)   ...  

The pinned post shows, but not the user comments, and when logged in as admin, no space to approve comments shows. How would I create the view for admins to approve comments and then have the comments rendered in the guest user view when approved?

Also, I should mention that comments can be made by anonymous users – a user does not have to be signed up or logged in.

Would appreciate any guidance on this. I can provide more code if required. Thanks.

Frosted glass effect using CSS for h2/h3 background area

Posted: 21 Jun 2016 06:02 AM PDT

I'm currently styling an events site and for the index page - representing each event I have an image with the event title and event date sat on top of the image. I currently have these in h2/h3 brackets, plain white text with a solid color background. I want to change the background to a 'frosted glass' effect using CSS. How do I do this?

Here's my current view Rails/html code and CSS styling -

index.html.erb - events

<div class="container">  <div class="row">      <div class="col-md-12">          <ul>                    <% @events.each do |event| %>              <li class="events">                       <%= link_to (image_tag event.image.url), event, id: "image" %>                  <div class="text">                        <h2><%= link_to event.title, event %></h2>                      <h3><%= link_to event.date.strftime('%A, %d %b %Y'), event %></h3>              </li>                         <% end %>                  </div>            </ul>                                 </div>  </div>    

events.css.scss -

li.events {   width: 350px;   height: 350px;   float: left;  margin: 20px;  list-style-type: none;  position: relative;      }     li.events img {   width: 100%;   height: 100%;   border-radius: 25px;         }    div.text  {     background: transparent;   padding: 25px;   position: absolute;   bottom: 15px;  left: 25px;     }    div.text a {  text-decoration: none;  color: #FFFFFF;  padding: 5px;     text-align: center;  border-radius: 15px;  background-color: #FF69B4;           }  

I imagine the image looking a bit like this (not the best screenshot - sorry). Frosted Glass background effect

Use shopify as a prelaunchr site

Posted: 21 Jun 2016 04:49 AM PDT

Pls let me know if I can use shopify as an prelaunchr site like harry's prelaunchr.what will be its requirments and so on.

Need help to set up jquery countdown in rails

Posted: 21 Jun 2016 05:19 AM PDT

I have made a Rails app to conduct a computer adaptive test. I need to put a timer in the exam so that exam gets over as soon as time is over. I have tried and searched all over the internet but couldn't find a solution. Thanks for your help :)

P.S.- Don't get angry if you think it is a childish question.

Rails Active Admin deployment cant log in "401 Unauthorized "

Posted: 21 Jun 2016 03:32 AM PDT

I have a problem with my Rails App (4.2.6) and Active Admin gem (latest). On my local development PC it is working well, but now when I tried to deploy to my custom VPC (where I have deployed few more testing apps) I am having trouble to log in within Active Admin Panel.

I am not getting any specific errors except this in screenshots:"401 Unauthorized"

enter image description here

Here are info about existing users (I have 2) and Yes I created one with AdminUser.create and another with User.create (I find some advice to do that, but not working in my case).

enter image description here

TweetStream: Exclude retweets

Posted: 21 Jun 2016 03:19 AM PDT

Trying to build a Twitter app based on https://github.com/tweetstream/tweetstream. But at http://www.rubydoc.info/gems/tweetstream/TweetStream/Client -- how'd I go about ignoring retweets?

This works

TweetStream::Client.new.follow(14252, 53235) do |status|    puts "#{status.text}"  end  

Failed attempt at excluding retweets #1

# both block arg and actual block given (SyntaxError)    TweetStream::Client.new.follow(14252, 53235).reject(&:retweet) do |status|    puts "#{status.text}"  end  

Failed attempt at excluding retweets #2

# No errors but also no tweets appearing    TweetStream::Client.new.follow(14252, 53235) do |status|    unless status.retweet      puts "#{status.text}"    end  end  

No comments:

Post a Comment