Saturday, May 7, 2016

Rails gem 'font-awesome-sass' vs gem 'font-awesome-rails' | Fixed issues

Rails gem 'font-awesome-sass' vs gem 'font-awesome-rails' | Fixed issues


Rails gem 'font-awesome-sass' vs gem 'font-awesome-rails'

Posted: 07 May 2016 06:58 AM PDT

I'm trying to integrate this bootstrap theme in my rails app. All seems to work well unless fonts; I've never used awesome-fonts before and I'm getting pretty confused. What's the difference between font-awesome-sass and font-awesome-rails? I've tryed both but nothing works. I don't get errors but fonts and icons are not loaded in the page.

Gemfile

gem 'rails', '4.2.6'  gem 'sqlite3'  gem 'sass-rails', '~> 5.0'  gem 'uglifier', '>= 1.3.0'  gem 'coffee-rails', '~> 4.1.0'  gem 'jquery-rails'  gem 'jquery-ui-rails'  gem 'turbolinks'  gem 'jbuilder', '~> 2.0'  gem 'sdoc', '~> 0.4.0', group: :doc  gem 'bootstrap-sass', '~> 3.3.6'  gem 'autoprefixer-rails'  gem 'font-awesome-sass'  gem 'font-awesome-rails'  

application.scss

@import "bootstrap-sprockets";  @import "bootstrap";  @import "font-awesome-sprockets";  @import "font-awesome";  @import "jquery-ui";  @import "agency";  

Rails page rendering time in a development environment

Posted: 07 May 2016 06:55 AM PDT

I'm just going to keep this question simple. In my rails console I see this:

Completed 200 OK in 2261ms (Views: 564.1ms | ActiveRecord: 40.7ms)  

Where do the 1656 milliseconds (2261 - 564 - 40) come from? Precompiling assets? This is in a dev environment.

Capistrano with multiple Puma applications

Posted: 07 May 2016 06:12 AM PDT

I want to deploy multiple rails applications to one Virtual Machine via capistrano.

Both applications in deploy.rb have that kind of setting:

set :puma_bind, "unix://#{shared_path}/tmp/sockets/#{fetch(:application)}-puma.sock"  

They have their own Nginx Config files.

First App:

upstream puma {     server unix:///var/www/first-app/shared/tmp/sockets/first-app-puma.sock;  }    server {     listen 80 default_server deferred;  

Second App:

upstream puma_second {    server unix:///var/www/second-app/shared/tmp/sockets/second-app-puma.sock;  }    server {    listen 81;  

First is on 80 port, second is on 81 port.

However, when I deploy second app then restart Nginx, then I open example.com:81, it shows me pages of first app without any styles.

Why this is happening? Do I need to bind second app to somewhere else?

nokogiri get text from <li> elements

Posted: 07 May 2016 06:12 AM PDT

let's say I have

<ul> <li>text1</li> <li>text2 </li> </ul>

Right now I get text from <li> like this:

result=    page.css(' ul li').text  

But the problem is that as a result I get string with no spaces like text1text2

I want it to be divided with <br> like this text1<br>text2<br> SO how do I do this?

Understanding Rails URL parameters

Posted: 07 May 2016 06:55 AM PDT

Apologies for the basic question, however I am completely new to Rails and am trying to debug an existing application.

Specifically, I am trying to reverse-engineer the URL, given the following controller:

def find_by_foo      params.require(:foo).permit(:bar1, :bar2)  end  

The route is as follows:

get 'find_by_foo', on: :collection  

And I even have a spec:

it "should not be successful" do      get :find_by_foo, params: {foo: BarStuff}      expect(response).to_not be_success      expect(response).to have_http_status(401)   end  

I am trying to figure out how to pass these parameters via my REST client. I have tried the following URL structures:

api/v1/collections/find_by_foo?foo={bar1: 0, bar2: 0}  api/v1/collections/find_by_foo/foo/0/0  api/v1/collections/find_by_foo?params={foo: {bar1: 0, bar2: 0}}  

All to now avail. What is the correct structure here?

Create user in devise without email and password in twitter omniauth

Posted: 07 May 2016 07:01 AM PDT

I want to do "Register with Twitter" in devise. I am using twitter-omniauth. I can't get email even I can't need it. But devise doesn't allow to create account without email.

User.rb

def self.from_omniauth(auth)  where(provider: auth.provider, uid: auth.uid).first_or_create! do |user|    user.email = auth.info.email    user.password = Devise.friendly_token[0,20]  end  

end

omniauth_controller.rb

def twitter auth = env["omniauth.auth"]

@user = User.from_omniauth(request.env["omniauth.auth"])  if @user.persisted?    sign_in_and_redirect @user, :event => :authentication    set_flash_message(:notice, :success, :kind => "Twitter") if is_navigational_format?  else    session["devise.twitter_uid"] = request.env["omniauth.auth"]    redirect_to new_user_registration_url  end  

end

How can I do it?

Jquery datepicker only working on chrome (Ruby On Rails)

Posted: 07 May 2016 05:47 AM PDT

I have a form with two inputs: The first is a datepicker and the second is a select picker with options appended to it when the user click on the datepicker. This is working great on chrome but neither on safari and firefox.

<div id="datepicker" class="public-holiday-date-pick">  </div>    <select class="form-control" id="appointment_date" name="appointment[date]">    <option value="">Veuillez chosir une date</option>  </select>  

My jquery code is here JSfiddle

I can't make it work on Jsfiddle but it's working on chrome on my rails app both in environnement and production environnement (but not on safari and firefox)

I use jQuery JavaScript Library v2.2.3 and jQuery UI Datepicker 1.10.3

Thank you if you have any tips.

How to do multiple domains applied to ruby on rails app

Posted: 07 May 2016 04:24 AM PDT

I'ved create a ruby on rails app.

And now I have several customers that want a white-label app for themselves.

Currently, it is on nginx server + puma (ruby on rails).

Is it possible to have different domains for the same Ruby On Rails app ? How do I accomplish such thing ?

domain1.com domain2.com domain3.com domain4.com

How to unsderstand rails5's actioncable

Posted: 07 May 2016 04:01 AM PDT

Recently I found that Rails5's ActionCable very interesting,So I want to dig into Rails5's ActionCable internels.But I didn't know where to begin.

I want someone pave the way for me: eg: what's the difference between ActionCable and faye and message_bus..do they use the same protocol like websockets?

NoMethodError in PostsController#create undefined method `latitude=' "saving lat and long to connected tables!!"

Posted: 07 May 2016 04:09 AM PDT

I am trying to post these coordinates from the metadata of the image i upload with paperclip to another table called places."so coordinates go to places table." There are columns latitude and longitude in the places table. After submitting the post i run into this error. The highlighted portion of the error is self.latitude=parse_latlong(etc....).

post_id is a foreign key in the places table. This worked previously when i had latitude and longitude in the post table. but now i gave it its own table for better database structure.. i just need to know how to get my post controller to work with my places controller if that is the main problem??

Places Controller

class PlacesController < ApplicationController      before_action :set_post    def create      @place = @post.places.build(place_params)        if @place.save      flash[:success] = "coorinates saved"      redirect_to :back    else      flash[:alert] = "Check the form, something went wrong."      render root_path    end  end      private    def place_params      params.require(:place).permit(:continent, :country, :city, :address, :latitude, :longitude)  end    def set_post      @post = Post.find(params[:post_id])  end    end  

post controller

class PostsController < ApplicationController    before_action :authenticate_user!, :except => [:show, :index, :new]    before_action :set_post, only: [:show, :edit, :update, :destroy]    before_action :owned_post, only: [:edit, :update, :destroy]        def index      @post = Post.new      @posts = Post.all    end      def show        @post = Post.find(params[:id])    end      def new      @post = current_user.posts.build        @posts = Post.all    end      def create       @post = current_user.posts.build(post_params)         if @post.save        flash[:success] = "Your post has been created!"        redirect_to root_path      else        flash[:alert] = "Your new post couldn't be created!  Please check the form."        render :new      end    end      def edit      @post = Post.find(params[:id])    end      def update       if @post.update(post_params)        flash[:success] = "Post updated."        redirect_to root_path      else        flash.now[:alert] = "Update failed.  Please check the form."        render :edit      end    end      def destroy      @post.destroy      flash[:success] = "Your Post has been removed."      redirect_to root_path    end      private      def post_params      params.require(:post).permit(:image, :caption, :address)    end      def set_post      @post = Post.find(params[:id])    end      def owned_post      unless current_user == @post.user      flash[:alert] = "That post doesn't belong to you!"      redirect_to root_path    end  end      end  

post model

class Post < ActiveRecord::Base    belongs_to :user  belongs_to :place    has_many :comments, dependent: :destroy  has_one :place, dependent: :destroy        validates :user_id, presence: true      validates :image, presence: true      accepts_nested_attributes_for :place      has_attached_file :image, styles: { :medium => "640x" }      validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/    after_post_process :save_latlong      private      def save_latlong    exif_data = MiniExiftool.new(image.queued_for_write[:original].path)    self.latitude = parse_latlong(exif_data['gpslatitude'])    self.longitude = parse_latlong(exif_data['gpslongitude'])  end    def parse_latlong(latlong)    return unless latlong    match, degrees, minutes, seconds, rotation = /(\d+) deg (\d+)' (.*)" (\w)/.match(latlong).to_a    calculate_latlong(degrees, minutes, seconds, rotation)  end    def calculate_latlong(degrees, minutes, seconds, rotation)    calculated_latlong = degrees.to_f + minutes.to_f/60 + seconds.to_f/3600    ['S', 'W'].include?(rotation) ? -calculated_latlong : calculated_latlong  end      end  

All in All i would like to get that latitude and longitude variable updated into the database from the exif extraction.. the extraction isn't the problem but instead I believe how Im saving that information into the database is the true problem!!! thank you!!!!

Use Rails Foundation for one module within an application

Posted: 07 May 2016 04:33 AM PDT

I'm working on application 'A' that's already built but foundation is not used. Now I need to work on another module 'B' that's within the same application 'A' but with foundation.

I have added gems 'compass-rails' & 'foundation-rails' in Gemfile and then run 'bundle install' & 'rails g foundation:install'.

Problem:

  • When I include "*= require foundation_and_overrides" in application.scss then it affects the entire application 'A'.

What is required:

  • I need to add "*= require foundation_and_overrides" only for module 'B' views so that the entire application won't get affected.

Queries:

  • Is there any possibility that we can use two different application.scss for rails application? Like I want to use A.scss (for application wide doesn't include foundation) and B.scss (only for module B with foundation).

Please help me out how I should cater this particular scenario.

Thanks in advance.

Checkbox styling - targeting a specific input element

Posted: 07 May 2016 03:41 AM PDT

Within a series of check boxes (lets say 3 options) I am looking to target a specific input element on the checking/unchecking of the associated label.

HAML

.choice-select-button    = check_box_tag("order[recipes][]", recipe.id, selected)    = label_tag do      = t(".step_4.tick_box_to_select")  

Renders HTML

<div class="choice-select-button">    <input type="checkbox" name="order[recipes][]" id="order_recipes_" value="6" checked="checked">    <label>Click to select</label>  </div>  

Each <input> is assigned same id, namely id="order_recipes_" so if I give set <label for="order_recipes_"> and the user then 'un-checks' the label then only the first input on the page with the id="order_recipes_" is styled according to my css instructions.

The only differentiator I can see for the choice-select-button.input is it's value. As such I was looking at giving the label a for= that targets inputs with the id="order_recipes_ AND value="6". First up, is this doable, and secondly, is the best way to do something like this or is there a much more simple method?

Thanks in advance.

Why my view is not showing in angular ui-view?

Posted: 07 May 2016 04:16 AM PDT

I am trying to wireup angularjs and rails. By following https://thinkster.io/angular-rails#angular-routing. I am not able to find out why my views is not showing up. I am getting empty page in browser.

**My routes**  angular.module('flapperNews', ['ui.router', 'templates']).config([  '$stateProvider', '$urlRouterProvider', function($stateProvider,     $urlRouterProvider){     $stateProvider        .state('home',{          url: '/home',          templateUrl: 'home/_home.html',          controller: 'MainCtrl',        resolve: {        postPromise: ['posts', function(posts){        return posts.getAll();       }]       }        })        .state('posts', {          url: '/posts/{id}',          templateUrl: 'posts/_posts.html',          controller: 'PostsCtrl',        resolve: {        post: ['$stateParams', 'posts', function($stateParams, posts) {        return posts.get($stateParams.id);       }]       }        });   $urlRouterProvider.otherwise('home');          }]);    Application.html.erb page    <!DOCTYPE html>  <html>  <head>  <title>FlapperNews</title>   <meta charset="utf-8"/>   <meta name="viewport" content="width=device-width, initial-scale=1.0">      <%= stylesheet_link_tag 'application', media: 'all' %>    <%= javascript_include_tag 'application' %>    <%= csrf_meta_tags %>    </head>    <body ng-app="flapperNews">   <div class="row">   <div class="col-md-6 col-md-offset-3">    <ui-view></ui-view   </div>   </div>   </body>   </html>     partial view  <div class="page-header">    <h1>Flapper News</h1>  </div>    <div ng-repeat="post in posts | orderBy:'-upvotes'">    <span class="glyphicon glyphicon-thumbs-up"      ng-click="incrementUpvotes(post)"></span>    {{post.upvotes}}    <span style="font-size:20px; margin-left:10px;">      <a ng-show="post.link" href="{{post.link}}">          {{post.title}}      </a>      <span ng-hide="post.link">        {{post.title}}      </span>    </span>    <span>    <a href="#/posts/{{post.id}}">Comments</a>    </span>  </div>    <form ng-submit="addPost()"    style="margin-top:30px;">    <h3>Add a new post</h3>      <div class="form-group">      <input type="text"      class="form-control"      placeholder="Title"      ng-model="title"></input>    </div>    <div class="form-group">      <input type="text"      class="form-control"      placeholder="Link"      ng-model="link"></input>    </div>    <button type="submit" class="btn btn-primary">Post</button>  </form>  

How to get a value fro a hash in rails

Posted: 07 May 2016 03:05 AM PDT

In my view:

<%= post.book %>  

gives me:

#<Book:0x007fbb885e94a8>  

I added inspect:

<%= post.book.inspect %>   

and I get:

#<Book id: 2, author: "Bob", created_at: "2016-05-07 05:19:04", updated_at: "2016-05-07 05:19:04">  

If I do <%= post.book.author %> I get:

undefined method `author' for nil:NilClass  

What I'm trying to display is just the author "Bob".

If I'm in the post/show view I can make it work with post.book.author, but I'm in a different view.

How do I connect to the thin server in faye-websocket?

Posted: 07 May 2016 02:20 AM PDT

I am migrating from websocket-rails to faye-websocket because of the need to scale with jruby in production, something that only the latter supports.

I'm finding the faye-websocket documentation very difficult to understand, but I've found this article that explains how to set up the connection. It explains how to set up a Websockets class in app/middleware/websockets.rb to open/close channels:

# app/middleware/websockets.rb  require 'faye/websocket'    class Websockets      KEEPALIVE_TIME = 15    attr_reader :clients, :base_channel      def initialize(app)      @app = app      # An array to hold all connected clients      @clients = []      # A base channel name used for pattern matching in Redis      @base_channel = "websockets"        # Must do this in a new thread because the following operations are       # blocking.      Thread.new do        # New connection to Redis        redis_sub = Redis.new          # Create a new pattern-based subscription that will listen for new messages on any channel        # that matches the pattern "websockets.*".        redis_sub.psubscribe("#{base_channel}.*") do |on|            # When a message is received, execute the send_message method          on.pmessage do |pattern, channel, msg|            send_message(channel, msg)          end          end      end      end      def call(env)      if Faye::WebSocket.websocket?(env)        # If the type of connection we're dealing with is a weboscket request,        # handle the connection.        setup_websocket_connection(env)      else        # Normal requests will continue through the call chain.        @app.call(env)      end    end      def send_message(channel, msg)      # For every client that has connected      clients.each do |client|          channel_name = channel.gsub("#{base_channel}.", "")          # If the client has requested a subscription to this channel        if client[:channels].include?(channel_name)            # Send the client the message, including the channel on which it          # was received.          message = "{\"channel\":\"#{channel_name}\",\"message\":#{msg}}"          client[:ws].send(message)        end      end    end      def new_client      # A client is represented here as a hash that has access to the Faye::Websocket      # object and an array of channels they care about.      { :ws => nil, :channels => [] }    end      def setup_websocket_connection(env)      ws = Faye::WebSocket.new(env, nil, { ping: KEEPALIVE_TIME })        # Create a new client      client = new_client        # Set up the "connection opened" event      websocket_connection_open(ws, client, env)      # Set up the "connection closed" event      websocket_connection_close(ws, client)        # Return the websocket rack response      ws.rack_response    end      def websocket_connection_open(ws, client, env)      request = Rack::Request.new(env)        # The list of channels the client is requesting access to      channels = request.params["channels"]      # A user token used for authentication      token = request.cookies["user_token"]        # When a connection has been opened      ws.on :open do |event|          # Assign the websocket object to the client        client[:ws] = ws          # For every channel the client wants to subscribe to...        channels.each do |channel|          # Ensure they are authorized to listen on this channel. (This is not          # needed, but useful if you want to add security to specific channels)          if WebsocketChannelAuthorizer.can_subscribe?(channel, token)            # Add the channel to the client            client[:channels].push(channel)          end        end          # Add the client to the list of clients        clients.push(client)      end      end      def websocket_connection_close(ws, client)      # When a client disconnects      ws.on :close do |event|        # Remove them from our list        clients.delete(client)        ws = nil      end    end    end  

and how to set up a WebsocketConnection wrapper that connects the client to the websocket server on ws://#{window.location.host}/:

# A simple Javascript wrapper class around the navtive WebSocket class.  # Written in CoffeeScript.    class WebsocketConnection      constructor: ->      @url = "ws://#{window.location.host}/"      @channels = {}      @events = {}      @status = "closed"      # Subscribe to a channel by name and supply a callback. Executing this    # method for the same channel multiple times will add multiple callbacks    # for when messages are received on that channel.    subscribe: (channel, callback) ->      @channels[channel] ?= []      @channels[channel].push(callback)      # Subscribe to a specific websocket events (open, close, and error) and     # supply a callback. Executing this method for the same event multiple     # times will add multiple callbacks for when the event is triggered.    on: (event, callback) ->      @events[event] ?= []      @events[event].push(callback)      # Opens a WebSocket connection    open: ->      return if @status == "open"        # Appends each channel to the URL via querystring. Example:          # ws://localhost/?channels[]=channel1&channels[]=channel2        # When the middelware receives this connection, it will take the channels      # sent through ?channels[] and add each one to that client.      url = "#{@url}?"      for name in Object.keys(@channels)        url += "channels[]=#{name}&"      url = url.substring(0, url.length - 1)        # Open the connection      @_connection = new WebSocket(url)        # Set up events      @_bindConnectionEvents()      @_bindChannelEvents()        # Start an interval to monitor the connection and ensure it stays open      @_keepAlive() unless @_keepAliveInterval      # Manually closes the connection    close: ->      return unless @_connection? && @status == "open"      # Stops the interval      clearInterval(@_keepAliveInterval) if @_keepAliveInterval      @_keepAliveInterval = null      @_connection.close()      # An interval that watches the connection's status every 5 seconds and tries     # to reopen it if the connection is closed.    _keepAlive: ->      self = this      @_keepAliveInterval = setInterval( ->        if self.status == 'closed'          self.open()      , 5000)      _bindConnectionEvents: ->      self = this        # When the connection is opened      @_connection.onopen = =>        # Update the status        @status = "open"        return unless self.events.open?          # Execute all the callbacks associated with the 'open' event        for callback in self.events.open          callback()        # When the connection is closed      @_connection.onclose = =>          # Update the status        @status = "closed"        return unless self.events.close?          # Execute all the callbacks associated with the 'close' event        for callback in self.events.close          callback()        # When the connection errors out      @_connection.onerror = =>        # Update the status        @status = "closed"        return unless self.events.error?          # Execute all the callbacks associated with the 'error' event        for callback in self.events.error          callback()      _bindChannelEvents: ->      # When a message is received on the WebSocket connection      @_connection.onmessage = (event) =>        # Parse the JSON        data = JSON.parse(event.data)        # Get the channel and messgae from the JSON body        channel = data.channel        message = data.message          return unless @channels[channel]?        # Execute each callback for that specific channel, passing the message        # to the callback        for callback in @channels[channel]          callback(message)  

In development I'm using thin, and according to the faye-websocket thin setup documentation I need to add the line Faye::WebSocket.load_adapter('thin'). Not quite sure where I'm supposed to put it, but as far as I understand it needs to be in app/config.ru before the run MyApp line.

I then power up thin start -R config.ru -p 9292, which is Listening on 0.0.0.0:9292.

Once I'v invoked the @connection = new WebsocketConnection() I check out console.log @connection, and it returns Object { url: "ws://my-app.dev/", channels: Object, events: Object, status: "closed" }. I am using pow - hence the .dev suffix. The on(:open) event is never triggered.

Do anyone have an idea what I'm missing?

Getting "undefined method `todo_item'"

Posted: 07 May 2016 03:18 AM PDT

Anyone can help solve this problem NoMethodError (undefined method `todo_items')?

This is my controller file:

 class Api::TodoItemsController < ApplicationController   skip_before_filter :verify_authenticity_token   before_filter :find_todo_list     def create     item = @list.todo_items.new(item_params)  if item.save    render status: 200, json: {      message: "Successfully created To-do Item.",      todo_list: @list,      todo_item: item    }.to_json  else    render status: 422, json: {      message: "To-do Item creation failed.",      errors: item.errors    }.to_json  end  end    private    def item_params    params.require("todo_item").permit("content")  end    def find_todo_list    @list = TodoList.find(params[:todo_list_id])  end  

end

This is my TodoList Model code:

class TodoList < ActiveRecord::Base  end  

This is my TodoItem Model code:

class TodoItem < ActiveRecord::Base  end  

This is error message of the undefined method todo_items:

Started POST "/api/todo_lists/5/todo_items/" for ::1 at 2016-05-07     16:57:45 +0800  ActiveRecord::SchemaMigration Load (0.1ms)  SELECT "schema_migrations".* FROM "schema_migrations"   Processing by Api::TodoItemsController#create as JSON   Parameters: {"content"=>"new", "todo_list_id"=>"5", "todo_item"=>{"content"=>"new"}}   TodoList Load (0.2ms)  SELECT  "todo_lists".* FROM "todo_lists" WHERE "todo_lists"."id" = ? LIMIT 1  [["id", 5]]   Completed 500 Internal Server Error in 21ms (ActiveRecord: 0.6ms)     NoMethodError (undefined method `todo_items' for #    <TodoList:0x007f82e2dbc088>):   app/controllers/api/todo_items_controller.rb:6:in `create'  

Thank you.

Rails 4/ Factory Girl - has_many/has_many factory and defining different objects

Posted: 07 May 2016 05:30 AM PDT

I'd like to define a factory for a has_many/has_many relationship (which I think I got it right) but I don't know how then to define attributes for each objects of these created factory.

Here is the homepage, it's a list of cards of deals

We assume the homepage view below is for a SIGNED-IN user (note current_user comes from Devise).

<% @deals.each do |deal| %>    @userdeal = UserDeal.where('user_id = ? AND deal_id = ?', current_user.id, deal.id).take        <div>        <div class="button">          <% if @userdeal.number_of_clicks = 4 %>you reached the maximum clicks          <% end %>        </div>        <div>          info for {user.deal id=5}        </div>        <div>          info for {user.deal id =17}        </div>      </div>    <% end %>  

Basically if a user has for a specific deal (on the table user_deals, see below the models) a user_deal.number_of_clicks = 4 then, on the card a button will appear with a message like "you reached the maximum clicks". if nb of clicks <4, no button appears.

So I want to use the factory on a Feature test where I'll check that if I create with fatcory girl one object @userdeal1 where the user reached 4 clicks, on this card he sees the button and its text, but for other deals he sees nothing.

Here's what I have so far

models

class Deal < ActiveRecord::Base    has_many   :user_deals,           dependent:  :destroy    has_many   :users,                through:    :user_deals  end    class User < ActiveRecord::Base    has_many :user_deals              has_many :deals,                through: :user_deals  end    class UserDeal < ActiveRecord::Base    belongs_to :user,         :foreign_key => 'user_id'    belongs_to :deal,         :foreign_key => 'deal_id'  end  

And the structure of the table user_deal

# Table name: user_deals  #  #  id                 :integer          not null, primary key  #  user_id            :integer  #  deal_id            :integer  #  number_of_clicks   :integer          default(0)  #  created_at         :datetime  #  updated_at         :datetime  

So far I found how to create

FactoryGirl.define do    factory :user_deal do      association :user      association :deal      end  

Following factorygirl ReadMe I created this:

FactoryGirl.define do    factory :user do        sequence(:email) { |n| "person#{n}@example.com"}         password "vddfdf"      password_confirmation "vddfdf"        confirmed_at Time.now        confirmation_token nil        factory :superadmin do        after(:create) {|user| user.add_role(:superadmin)}      end        after(:create) do |user|        user.deals << FactoryGirl.create(:deal)      end        factory :user_with_deals do        # used for defining user_deals        transient do          deals_count 5         end        after(:create) do |user, evaluator|          create_list(:deal, evaluator.deals_count, user: user)        end      end      end  end  

But now I don't know how to say 'ok of one of these created user_deals in the factory, I'd like one to have number_of_clicks =4, and the other one number_of_clicks=1). so I tried to put this inside the test directly , as below:

describe 'HP deal card features', :type => :feature do        context "As signed-in USER" do      let(:subject) { ApplicationController.new }        before do               @user = FactoryGirl.create(:user, :user_country_name => 'Germany')         @deal1   = FactoryGirl.build( :deal)        @deal2  = FactoryGirl.build( :deal)        @user_deal_with_max_of_clicks = FactoryGirl.build( :user_with_deals,                                                              :user             => @user,                                                              :deal             => @deal1,  :number_of_clicks => 4                                                          ).save(validate: false)        @user_deale_with_clicks_available = FactoryGirl.build( :user_with_deals,                                                              :user             => @user,                                                              :deal             => @deal2,  number_of_clicks => 1 # still has clicks                                                          ).save(validate: false)      it "the right behavior for the buttons telling him how many clicks he has left" do          sign_in @user        visit root_path        I'll find a way to test here if there is the text "you reached the maximum clicks" for the first card and not for the second         end      after do        visit destroy_user_session_path      end      end  

But the test does not work and give me different type of errors according to the small change I try. I am pretty sure I don't manage to really create the 2 objects user_deals , one with number_of_clicks= 4 and the other one number_of_clicks= 1.

Rails server doesn't start in production

Posted: 07 May 2016 02:48 AM PDT

I'm trying to start my first production rails server on DigitalOcean but after

$ rails server — binding=my_Droplet_ip_address  

i get this error

Exiting  /home/username/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/handler.rb:78:in `require': cannot load such file -- rack/handler/— (LoadError)  from /home/glaux/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/handler.rb:78:in `try_require'      from /home/glaux/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/handler.rb:16:in `get'      from /home/glaux/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/server.rb:290:in `server'  

And so on.

App works fine locally and simple rails s on server also works fine.

I have Ubuntu 14.04 server with postgres, nginx and passenger.

I'm a complete newbie to it and I may have missed something important. So tell me if you want me to provide any other info on this matter.

Devise model without devise routes

Posted: 07 May 2016 01:38 AM PDT

I have two Rails projects sharing some files, one is the actual app and the other one is the admin tool for the app. They share migrations, models, some config, etc. The admin tools is ActiveAdmin 1.0.0-pre2 and Rails' version is 4.2.

I have two Devise models, User and AdminUser. In the app project, there's no route for admin_user and I want to keep it that way, but if I don't add:

devise_for :admin_users  

to the routes file, I get all sort of strange errors, such as:

ActionView::Template::Error: undefined method `admin_user_confirmation_url' for #<ActionDispatch::Routing::RoutesProxy:0x007fc613ecde08>  

or:

Could not find a valid mapping for <AdminUser ...>  

whenever I'm creating an AdminUser in the app project (sample data generation).

How can I achieve having a devise model, without the routes?

collection_select from entities with specific attibute

Posted: 07 May 2016 01:15 AM PDT

Hi I have the following collection_select tag:

<%=collection_select(:post, :applicant_id, Room.all, :room_number, :room_number, {selected: @applicant.room_number}, { :onchange=>"window.location='#{room_select_path(@applicant.id)}?room_number=' + this.value"})%>  

Currently, it displays all room entities available.

What I want to do is to display all room entities with the attribute :room_type.

RubyMine ignores rbenv setting

Posted: 07 May 2016 12:08 AM PDT

I have rbenv installed and rbenv global is 2.3.0. However when I open a rails project I haven't previously opened in RubyMine, it doesn't pick up the ruby version from rbenv, instead it uses the older version of ruby installed. Is this a bug in RubyMine or am I missing something?

missing required keys: [:id] rails

Posted: 07 May 2016 01:49 AM PDT

when I try to run my code, I got the problem above. Here's my tasks/_task.html.erb

<% @list.tasks.each do |task| %>      <p>          <%= task.name %><%= task.id %>          <%= link_to "Destroy", to_do_list_task_path(@list, task.id), method: :delete %>      </p>  <% end %>  

my tasks controller :

def destroy      @list = ToDoList.find(params[:to_do_list_id])      @task = @list.tasks.find(params[:id])      if @task.destroy          redirect_to(:back)      else          redirect_to(:back)      end  end  

and my routes :

resources :to_do_lists do      resources :tasks  end  

full error :

No route matches {:action=>"show", :controller=>"tasks", :id=>nil, :to_do_list_id=>"157"} missing required keys: [:id]  

Any idea ?

EDIT to_do_list's controller :

def show      @list = @user.to_do_lists.find(params[:id])      @task = @list.tasks.new      @build = @list.tasks.build  end  

EDIT 2 full error :

[localhost] [::1] [6d1ad8d6-bfdf-4c] Started GET "/to_do_lists/158" for ::1 at 2016-05-07 09:14:37 +0200  [localhost] [::1] [6d1ad8d6-bfdf-4c] Started GET "/to_do_lists/158" for ::1 at 2016-05-07 09:14:37 +0200  [localhost] [::1] [6d1ad8d6-bfdf-4c] Processing by     ToDoListsController#show as HTML  [localhost] [::1] [6d1ad8d6-bfdf-4c] Processing by ToDoListsController#show as HTML  [localhost] [::1] [6d1ad8d6-bfdf-4c]   Parameters: {"id"=>"158"}  [localhost] [::1] [6d1ad8d6-bfdf-4c]   Parameters: {"id"=>"158"}  [localhost] [::1] [6d1ad8d6-bfdf-4c]   User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 24]]  [localhost] [::1] [6d1ad8d6-bfdf-4c]   User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 24]]  [localhost] [::1] [6d1ad8d6-bfdf-4c]   ToDoList Load (0.4ms)  SELECT  "to_do_lists".* FROM "to_do_lists" WHERE "to_do_lists"."user_id" = $1 AND "to_do_lists"."id" = $2 LIMIT 1  [["user_id", 24], ["id", 158]]  [localhost] [::1] [6d1ad8d6-bfdf-4c]   ToDoList Load (0.4ms)  SELECT  "to_do_lists".* FROM "to_do_lists" WHERE "to_do_lists"."user_id" = $1 AND "to_do_lists"."id" = $2 LIMIT 1  [["user_id", 24], ["id", 158]]  [localhost] [::1] [6d1ad8d6-bfdf-4c]    (0.3ms)  SELECT COUNT(*) FROM "tasks" WHERE "tasks"."to_do_list_id" = $1  [["to_do_list_id", 158]]  [localhost] [::1] [6d1ad8d6-bfdf-4c]    (0.3ms)  SELECT COUNT(*) FROM "tasks" WHERE "tasks"."to_do_list_id" = $1  [["to_do_list_id", 158]]  [localhost] [::1] [6d1ad8d6-bfdf-4c]   Task Load (0.4ms)  SELECT "tasks".* FROM "tasks" WHERE "tasks"."to_do_list_id" = $1   [["to_do_list_id", 158]]  [localhost] [::1] [6d1ad8d6-bfdf-4c]   Task Load (0.4ms)  SELECT "tasks".* FROM "tasks" WHERE "tasks"."to_do_list_id" = $1  [["to_do_list_id", 158]]  [localhost] [::1] [6d1ad8d6-bfdf-4c]   Rendered tasks/_task.html.erb (5.3ms)  [localhost] [::1] [6d1ad8d6-bfdf-4c]   Rendered tasks/_task.html.erb (5.3ms)  [localhost] [::1] [6d1ad8d6-bfdf-4c]   Rendered to_do_lists/show.html.erb within layouts/application (7.6ms)  [localhost] [::1] [6d1ad8d6-bfdf-4c]   Rendered to_do_lists/show.html.erb within layouts/application (7.6ms)  [localhost] [::1] [6d1ad8d6-bfdf-4c] Completed 500 Internal Server Error in 17ms (ActiveRecord: 1.4ms)  [localhost] [::1] [6d1ad8d6-bfdf-4c] Completed 500 Internal Server Error in 17ms (ActiveRecord: 1.4ms)  [localhost] [::1] [6d1ad8d6-bfdf-4c]  ActionView::Template::Error (No route matches {:action=>"show", :controller=>"tasks", :id=>nil, :to_do_list_id=>"158"} missing required keys: [:id]):  2:  <% @list.tasks.each do |task| %>  3:      <p>  4:          <%= task.name %><%= task.id %>  5:          <%= link_to "Supprimer", to_do_list_task_path(@list, task), method: :delete %>  6:      </p>  7:  <% end %>  8: </div>    app/views/tasks/_task.html.erb:5:in `block in    _app_views_tasks__task_html_erb___979180469130099435_70290175534220'    app/views/tasks/_task.html.erb:2:in `_app_views_tasks__task_html_erb___979180469130099435_70290175534220'    app/views/to_do_lists/show.html.erb:7:in `_app_views_to_do_lists_show_html_erb__2820495566946140584_70290199271140'  

Deleting file at end of Chef run

Posted: 06 May 2016 11:36 PM PDT

I want to delete file at the end of Chef run.
I am using the following file resource to achieve that

file "#{home_dir['data']}/file1.txt" do    action :delete    retries 3    retry_delay 50    only_if { ::File.exist? "#{home_dir['data']}/file1.txt" }  end  

Please let me know if there is a better way to achieve it.

How to use OmniAuth only for authorization from different Apis without authentication in Ruby on Rails

Posted: 06 May 2016 11:27 PM PDT

I want to use OmniAuth to retrieve user access_token and secret from facebook , twitter and google at the same time.

I'm using Devise for authentication , and I want to know how to request keys when the user is signed in and store them in a database to use them later .

How do I stop rake from treating a file dependency as a possible task name?

Posted: 06 May 2016 11:53 PM PDT

Short version:

I have a problem: a file dependency I need for one rake task matches the name of another rake task, so instead of depending on the file, rake tries to depend on the task with the matching name.

How do I tell rake to only match a dependency to a file? Is there some other way out?

Long version:

I'm trying to create a rake task in my Rails application that zips up all the files I care about. That's it. Easy.

I'd also appreciate the normal dependency testing in rake: if no files have changed and the zip file already exists, don't do anything.

The issue is that one of the files that I want to include in the zip file (and thus treat as a task dependency) is the test directory, but rake test happens to be an existing rake task. If I say something like:

# FILES_TO_INCLUDE being a Rake::FileList...  file 'output.zip' => FILES_TO_INCLUDE.to_a do    ...  end  

rake ends up running rake test as well.

Since I add files all the time, and since Rails changes the built-in rake tasks every now and then, I can never be sure that there won't be a conflict between rake tasks and file names.

What can I do to avoid this issue? Is there a better usage of rake that I'm missing?

Heroku will not update assets

Posted: 06 May 2016 10:49 PM PDT

My Heroku app will not update assets when I push to Heroku, I have exhausted all posts regarding this issue on stack overflow, but nothing works. rake assets:precompile doesn't work either, I have tried deleting the public/assets folder, checked all the config settings in production.rb, and nothing will work. Funny thing is is that it has worked fine for weeks, and for some reason something I did today caused this problem. I know this is vague, I was hoping someone might have some info or suggestions. Thanks, any help would be really appreciated.

Heroku Logs:

2016-05-07T05:16:31.292801+00:00 app[web.1]:   Rendered layouts/_header_nav.html.erb (1.1ms)  2016-05-07T05:16:31.293093+00:00 app[web.1]: Completed 200 OK in 19ms (Views: 14.0ms | ActiveRecord: 3.6ms)  2016-05-07T05:16:31.292818+00:00 app[web.1]:   Rendered layouts/_header_nav.html.erb (1.1ms)  2016-05-07T05:16:31.293125+00:00 app[web.1]: Completed 200 OK in 19ms (Views: 14.0ms | ActiveRecord: 3.6ms)  2016-05-07T05:16:31.414629+00:00 heroku[router]: at=info method=GET path="/assets/cornerstone1-2ee8a814bfa98e11d50e198146dab57a.png" host=cornerstone-demo1.herokuapp.com request_id=dacfdbf6-f207-4598-a324-ef58eba8f35e fwd="69.245.139.238" dyno=web.1 connect=4ms service=4ms status=304 bytes=133  2016-05-07T05:16:31.354598+00:00 heroku[router]: at=info method=GET path="/assets/application-8180715104539ca4199f4ba92d360674.css" host=cornerstone-demo1.herokuapp.com request_id=5bcf5efb-d9f0-425f-ab06-e9ffe9656298 fwd="69.245.139.238" dyno=web.1 connect=1ms service=4ms status=304 bytes=133  2016-05-07T05:16:31.539477+00:00 heroku[router]: at=info method=GET path="/assets/cornerstone-cd9f88d8384c02f37560fa75a673fc0b.png" host=cornerstone-demo1.herokuapp.com request_id=4e14df4f-dcd2-474f-93cb-c946418c5743 fwd="69.245.139.238" dyno=web.1 connect=1ms service=14ms status=304 bytes=133  2016-05-07T05:16:31.529049+00:00 heroku[router]: at=info method=GET path="/assets/fontawesome-webfont.woff2?v=4.5.0" host=cornerstone-demo1.herokuapp.com request_id=2cb04d53-59d3-4de9-806d-567b840256a6 fwd="69.245.139.238" dyno=web.1 connect=1ms service=7ms status=304 bytes=231  2016-05-07T05:16:31.531995+00:00 app[web.1]: Started GET "/assets/fontawesome-webfont.woff2?v=4.5.0" for 69.245.139.238 at 2016-05-07 05:16:31 +0000  2016-05-07T05:16:31.533832+00:00 app[web.1]: Started GET "/assets/fontawesome-webfont.woff2?v=4.5.0" for 69.245.139.238 at 2016-05-07 05:16:31 +0000  2016-05-07T05:16:32.457544+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=cornerstone-demo1.herokuapp.com request_id=b5ec5659-9e76-438c-8344-c6b5e1dcce26 fwd="69.245.139.238" dyno=web.1 connect=1ms service=5ms status=200 bytes=228  2016-05-07T05:17:36.852719+00:00 heroku[api]: Release v76 created by anthonydevenuto@gmail.com  2016-05-07T05:17:37.023854+00:00 heroku[slug-compiler]: Slug compilation started  2016-05-07T05:17:37.023864+00:00 heroku[slug-compiler]: Slug compilation finished  2016-05-07T05:17:36.852719+00:00 heroku[api]: Deploy 36e75de by anthonydevenuto@gmail.com  2016-05-07T05:17:37.031909+00:00 heroku[web.1]: State changed from up to starting  2016-05-07T05:17:37.031232+00:00 heroku[web.1]: Restarting  2016-05-07T05:17:40.505988+00:00 heroku[web.1]: Stopping all processes with SIGTERM  2016-05-07T05:17:41.653522+00:00 app[web.1]: [2016-05-07 05:17:41] FATAL SignalException: SIGTERM  2016-05-07T05:17:41.653533+00:00 app[web.1]:    /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/webrick/server.rb:174:in `select'  2016-05-07T05:17:41.653534+00:00 app[web.1]:    /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/webrick/server.rb:174:in `block in start'  2016-05-07T05:17:41.653535+00:00 app[web.1]:    /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/webrick/server.rb:32:in `start'  2016-05-07T05:17:41.653535+00:00 app[web.1]:    /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/webrick/server.rb:162:in `start'  2016-05-07T05:17:41.653536+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/handler/webrick.rb:14:in `run'  2016-05-07T05:17:41.653537+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/server.rb:264:in `start'  2016-05-07T05:17:41.653538+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.2.0/gems/railties-4.0.1/lib/rails/commands/server.rb:84:in `start'  2016-05-07T05:17:41.653539+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.2.0/gems/railties-4.0.1/lib/rails/commands.rb:76:in `block in <top (required)>'  2016-05-07T05:17:41.653539+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.2.0/gems/railties-4.0.1/lib/rails/commands.rb:71:in `tap'  2016-05-07T05:17:41.653541+00:00 app[web.1]:    bin/rails:4:in `require'  2016-05-07T05:17:41.653540+00:00 app[web.1]:    /app/vendor/bundle/ruby/2.2.0/gems/railties-4.0.1/lib/rails/commands.rb:71:in `<top (required)>'  2016-05-07T05:17:41.653541+00:00 app[web.1]:    bin/rails:4:in `<main>'  2016-05-07T05:17:41.653879+00:00 app[web.1]: [2016-05-07 05:17:41] INFO  going to shutdown ...  2016-05-07T05:17:41.653957+00:00 app[web.1]: [2016-05-07 05:17:41] INFO  WEBrick::HTTPServer#start done.  2016-05-07T05:17:41.654031+00:00 app[web.1]: Exiting  2016-05-07T05:17:42.746817+00:00 heroku[web.1]: Process exited with status 143  2016-05-07T05:17:44.245740+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 8857 -e production`  2016-05-07T05:17:47.115932+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.0.1/lib/active_support/values/time_zone.rb:282: warning: circular argument reference - now  2016-05-07T05:17:48.157947+00:00 app[web.1]: Digest::Digest is deprecated; use Digest  2016-05-07T05:17:48.650999+00:00 app[web.1]: Digest::Digest is deprecated; use Digest  2016-05-07T05:17:49.126857+00:00 app[web.1]: [2016-05-07 05:17:49] INFO  WEBrick 1.3.1  2016-05-07T05:17:49.126871+00:00 app[web.1]: [2016-05-07 05:17:49] INFO  ruby 2.2.4 (2015-12-16) [x86_64-linux]  2016-05-07T05:17:49.127242+00:00 app[web.1]: [2016-05-07 05:17:49] INFO  WEBrick::HTTPServer#start: pid=3 port=8857  2016-05-07T05:17:49.256320+00:00 heroku[web.1]: State changed from starting to up  2016-05-07T05:17:51.170593+00:00 app[web.1]: => Booting WEBrick  2016-05-07T05:17:51.170611+00:00 app[web.1]: => Rails 4.0.1 application starting in production on http://0.0.0.0:8857  2016-05-07T05:17:51.170612+00:00 app[web.1]: => Run `rails server -h` for more startup options  2016-05-07T05:17:51.170613+00:00 app[web.1]: => Ctrl-C to shutdown server  2016-05-07T05:17:51.170613+00:00 app[web.1]: Started GET "/locations/3" for 69.245.139.238 at 2016-05-07 05:17:51 +0000  2016-05-07T05:17:51.170618+00:00 app[web.1]: Started GET "/locations/3" for 69.245.139.238 at 2016-05-07 05:17:51 +0000  2016-05-07T05:17:51.790607+00:00 app[web.1]: Processing by LocationsController#show as HTML  2016-05-07T05:17:51.790618+00:00 app[web.1]: Processing by LocationsController#show as HTML  2016-05-07T05:17:51.790662+00:00 app[web.1]:   Parameters: {"id"=>"3"}  2016-05-07T05:17:51.790685+00:00 app[web.1]:   Parameters: {"id"=>"3"}  2016-05-07T05:17:51.883230+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/activerecord-4.0.1/lib/active_record/associations/has_many_association.rb:76: warning: circular argument reference - reflection  2016-05-07T05:17:51.883243+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/activerecord-4.0.1/lib/active_record/associations/has_many_association.rb:80: warning: circular argument reference - reflection  2016-05-07T05:17:51.883272+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/activerecord-4.0.1/lib/active_record/associations/has_many_association.rb:84: warning: circular argument reference - reflection  2016-05-07T05:17:51.883344+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/activerecord-4.0.1/lib/active_record/associations/has_many_association.rb:103: warning: circular argument reference - reflection  2016-05-07T05:17:52.272350+00:00 heroku[router]: at=info method=GET path="/locations/3" host=cornerstone-demo1.herokuapp.com request_id=0e46b486-2914-42d4-b299-05a80530a8f8 fwd="69.245.139.238" dyno=web.1 connect=47ms service=1152ms status=304 bytes=811  2016-05-07T05:17:52.226133+00:00 app[web.1]:   Rendered locations/_pierhouse_at_channelside.html.erb (115.5ms)  2016-05-07T05:17:52.228545+00:00 app[web.1]:   Rendered locations/_pierhouse_at_channelside.html.erb (115.5ms)  2016-05-07T05:17:52.251344+00:00 app[web.1]:   Rendered layouts/_footer.html.erb (5.1ms)  2016-05-07T05:17:52.251499+00:00 app[web.1]:   Rendered locations/show.html.erb within layouts/application (389.4ms)  2016-05-07T05:17:52.251391+00:00 app[web.1]:   Rendered layouts/_footer.html.erb (5.1ms)  2016-05-07T05:17:52.255676+00:00 app[web.1]:   Rendered layouts/_header_nav.html.erb (2.5ms)  2016-05-07T05:17:52.251538+00:00 app[web.1]:   Rendered locations/show.html.erb within layouts/application (389.4ms)  2016-05-07T05:17:52.255695+00:00 app[web.1]:   Rendered layouts/_header_nav.html.erb (2.5ms)  2016-05-07T05:17:52.255962+00:00 app[web.1]: Completed 200 OK in 465ms (Views: 95.8ms | ActiveRecord: 322.5ms)  2016-05-07T05:17:52.255978+00:00 app[web.1]: Completed 200 OK in 465ms (Views: 95.8ms | ActiveRecord: 322.5ms)  2016-05-07T05:17:52.600120+00:00 heroku[router]: at=info method=GET path="/assets/cornerstone1-2ee8a814bfa98e11d50e198146dab57a.png" host=cornerstone-demo1.herokuapp.com request_id=3e14b615-4727-485b-817e-311e5cfb576e fwd="69.245.139.238" dyno=web.1 connect=2ms service=4ms status=200 bytes=6179  2016-05-07T05:17:52.611710+00:00 heroku[router]: at=info method=GET path="/assets/application-8180715104539ca4199f4ba92d360674.css" host=cornerstone-demo1.herokuapp.com request_id=9e0655ad-2de7-4b67-b32a-39b6fdd64945 fwd="69.245.139.238" dyno=web.1 connect=1ms service=48ms status=200 bytes=603146  2016-05-07T05:17:52.612205+00:00 heroku[router]: at=info method=GET path="/assets/application-9c3a4055adfbab4cc780f4ee83cc292c.js" host=cornerstone-demo1.herokuapp.com request_id=873146b9-7dac-4d72-a32d-daacf2382544 fwd="69.245.139.238" dyno=web.1 connect=1ms service=60ms status=200 bytes=882117  2016-05-07T05:17:53.198746+00:00 heroku[router]: at=info method=GET path="/assets/cornerstone-cd9f88d8384c02f37560fa75a673fc0b.png" host=cornerstone-demo1.herokuapp.com request_id=d44499a3-1f65-4b7f-b032-0104a9a0d846 fwd="69.245.139.238" dyno=web.1 connect=34ms service=35ms status=200 bytes=5967  2016-05-07T05:17:53.861416+00:00 heroku[router]: at=info method=GET path="/assets/fontawesome-webfont.woff2?v=4.5.0" host=cornerstone-demo1.herokuapp.com request_id=8f0bbe79-5e69-4326-88da-526bea7f8803 fwd="69.245.139.238" dyno=web.1 connect=38ms service=59ms status=304 bytes=231  2016-05-07T05:17:53.855975+00:00 app[web.1]: Started GET "/assets/fontawesome-webfont.woff2?v=4.5.0" for 69.245.139.238 at 2016-05-07 05:17:53 +0000  2016-05-07T05:17:53.856049+00:00 app[web.1]: Started GET "/assets/fontawesome-webfont.woff2?v=4.5.0" for 69.245.139.238 at 2016-05-07 05:17:53 +0000  2016-05-07T05:17:54.573443+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=cornerstone-demo1.herokuapp.com request_id=a3058d34-bd90-457c-a8bf-8e58777b8d7d fwd="69.245.139.238" dyno=web.1 connect=44ms service=53ms status=200 bytes=228  2016-05-07T05:28:04.296846+00:00 heroku[router]: at=info method=GET path="/assets/application-8180715104539ca4199f4ba92d360674.css" host=cornerstone-demo1.herokuapp.com request_id=597d59f7-fb6a-4844-ba2f-1e36a7e54dfb fwd="69.245.139.238" dyno=web.1 connect=0ms service=4ms status=304 bytes=133  2016-05-07T05:28:04.309977+00:00 heroku[router]: at=info method=GET path="/assets/application-9c3a4055adfbab4cc780f4ee83cc292c.js" host=cornerstone-demo1.herokuapp.com request_id=3add85bb-5e93-482a-8412-a347ef56de53 fwd="69.245.139.238" dyno=web.1 connect=3ms service=5ms status=304 bytes=133  2016-05-07T05:28:04.236456+00:00 heroku[router]: at=info method=GET path="/locations/3" host=cornerstone-demo1.herokuapp.com request_id=77c31ad5-5a0b-4e8a-92c6-6cd1a22f93e8 fwd="69.245.139.238" dyno=web.1 connect=1ms service=30ms status=304 bytes=811  2016-05-07T05:28:04.350288+00:00 heroku[router]: at=info method=GET path="/assets/cornerstone1-2ee8a814bfa98e11d50e198146dab57a.png" host=cornerstone-demo1.herokuapp.com request_id=a52349be-0ee2-4cb6-b766-5aaa0654029d fwd="69.245.139.238" dyno=web.1 connect=0ms service=3ms status=304 bytes=133  2016-05-07T05:28:04.211499+00:00 app[web.1]: Started GET "/locations/3" for 69.245.139.238 at 2016-05-07 05:28:04 +0000  2016-05-07T05:28:04.211536+00:00 app[web.1]: Started GET "/locations/3" for 69.245.139.238 at 2016-05-07 05:28:04 +0000  2016-05-07T05:28:04.213216+00:00 app[web.1]: Processing by LocationsController#show as HTML  2016-05-07T05:28:04.213243+00:00 app[web.1]: Processing by LocationsController#show as HTML  2016-05-07T05:28:04.236406+00:00 app[web.1]:   Rendered layouts/_header_nav.html.erb (0.7ms)  2016-05-07T05:28:04.213319+00:00 app[web.1]:   Parameters: {"id"=>"3"}  2016-05-07T05:28:04.232382+00:00 app[web.1]:   Rendered locations/_pierhouse_at_channelside.html.erb (12.9ms)  2016-05-07T05:28:04.235018+00:00 app[web.1]:   Rendered layouts/_footer.html.erb (0.9ms)  2016-05-07T05:28:04.235151+00:00 app[web.1]:   Rendered locations/show.html.erb within layouts/application (19.1ms)  2016-05-07T05:28:04.236607+00:00 app[web.1]: Completed 200 OK in 23ms (Views: 18.5ms | ActiveRecord: 3.7ms)  2016-05-07T05:28:04.236630+00:00 app[web.1]: Completed 200 OK in 23ms (Views: 18.5ms | ActiveRecord: 3.7ms)  2016-05-07T05:28:04.213305+00:00 app[web.1]:   Parameters: {"id"=>"3"}  2016-05-07T05:28:04.234994+00:00 app[web.1]:   Rendered layouts/_footer.html.erb (0.9ms)  2016-05-07T05:28:04.232368+00:00 app[web.1]:   Rendered locations/_pierhouse_at_channelside.html.erb (12.9ms)  2016-05-07T05:28:04.235125+00:00 app[web.1]:   Rendered locations/show.html.erb within layouts/application (19.1ms)  2016-05-07T05:28:04.236417+00:00 app[web.1]:   Rendered layouts/_header_nav.html.erb (0.7ms)  2016-05-07T05:28:04.418835+00:00 heroku[router]: at=info method=GET path="/assets/cornerstone-cd9f88d8384c02f37560fa75a673fc0b.png" host=cornerstone-demo1.herokuapp.com request_id=19d4f07e-9b7a-4a11-9fc4-8ba1d4a5faa9 fwd="69.245.139.238" dyno=web.1 connect=0ms service=3ms status=304 bytes=133  2016-05-07T05:28:04.468996+00:00 heroku[router]: at=info method=GET path="/assets/fontawesome-webfont.woff2?v=4.5.0" host=cornerstone-demo1.herokuapp.com request_id=09895c53-517c-4a98-9362-aa53fd3e5444 fwd="69.245.139.238" dyno=web.1 connect=0ms service=4ms status=304 bytes=231  2016-05-07T05:28:04.469569+00:00 app[web.1]: Started GET "/assets/fontawesome-webfont.woff2?v=4.5.0" for 69.245.139.238 at 2016-05-07 05:28:04 +0000  2016-05-07T05:28:04.469585+00:00 app[web.1]: Started GET "/assets/fontawesome-webfont.woff2?v=4.5.0" for 69.245.139.238 at 2016-05-07 05:28:04 +0000  2016-05-07T05:28:05.121207+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=cornerstone-demo1.herokuapp.com request_id=0a78e2a4-d39d-43b0-a110-619e296ffb71 fwd="69.245.139.238" dyno=web.1 connect=0ms service=3ms status=200 bytes=228  

How to insert document field value as ISODate with Ruby MongoDB driver?

Posted: 06 May 2016 09:32 PM PDT

It may be really simple, but the obvious is elusive at the moment in Ruby land.

How do I insert document field value as ISODate and NOT a string with Ruby MongoDB driver? When I query a collection inside the MongoDB shell, I want the timestamp to be an ISODate object:

{    "_id": ObjectId("570348904b3833000addcd67"),    "timestamp": ISODate("2016-04-04T21:23:52.058Z")  }  

And NOT:

{    "_id": ObjectId("570348904b3833000addcd67"),    "timestamp": "2016-04-04T21:23:52.058Z" // or ms since epoch  }  

Please don't suggest I use ms|s since epoch. It's not a solution here.

Thanks for your help, S.O.!

How to pass create form builder in ajax redirect

Posted: 07 May 2016 02:37 AM PDT

I have on change ajax event, that reloads a partial, to build nested attributes, based on the selected item.

The reloaded partial looks like this(I have cut most of it since it is not important):

      = f.fields_for :skill_of_objects, @character.skill_of_objects.build do |ff|          %strong            = school_skill.skill.name_pl          = ff.hidden_field :skill_id, value: school_skill.skill.id          = ff.label :value  

The problem is the f builder.

I have done some stack research, and based on the last answer from >> this question I have ended in something like this:

'<%= form_for [current_user, @character] do |f| %>'    $('#school_skills').html("<%= j render( partial: 'school_skills', locals: {f: f}) %>");  '<% end %>'  

But I still get error like this:

ActionView::Template::Error (undefined local variable or method `f' for #<#<Class:0xca1eb70>:0xd0811c0>):  

Any suggestions would be appreciated :)

The form is a partial _character_form.html.haml in the new.html.haml file located in views/characters folder.

_character_form.html.haml file looks like this:

= form_for [ current_user, @character], remote: true do |f|    = form_errors_for @character    %ul.no_dot      %li        = f.label(:name, 'Imię Postaci:')        = f.text_field(:name)      %li{id: 'clan_select'}        = render 'character_form_clan'      %li{id: 'family_select'}        = render 'character_form_families'      %li{id: 'school_select'}        = render 'character_form_schools'      %li        = render 'character_attributes', f: f      %li{id: 'character_honour'}        = render 'character_honour'      %li{id: 'character_outfit'}        = render 'character_outfit'      %li        %strong          Umiejętności:        %div{id: 'school_skills'}          = render 'school_skills', f: f      %li        = f.hidden_field(:family_bonus, value: @selected_family.bonus_attr)      %li        = f.hidden_field( :school_bonus, value: @selected_school.bonus_attr)      %li        = f.submit "Dodaj Postać"  

The ajax is trigered by coffeescript:

$(document).on 'change', '#character_clan_id', ->    $.ajax      url: 'on_clan_change'      type: 'GET'      dataType: 'script'      data: {        clan_id: $("#character_clan_id option:selected").val(),        school_bonus: $("#character_school_bonus").val(),        family_bonus: $("#character_family_bonus").val() }  

character_controller new and on_clan_change action (there are also on_family_change and on_school_change ajax actions):

   def new      @character = Character.new      @clan = Clan.first      @families = @clan.families.order(:clan_name)      @selected_family = @families.first      @schools = @clan.basic_schools.order(:name)      @selected_school = @schools.first    end    def on_clan_change      @character = Character.new      @clan = Clan.find(params[:clan_id])      @families = @clan.families.order(:clan_name)      @selected_family = @families.first      @schools = @clan.basic_schools.order(:name)      @selected_school = @schools.first      @old_school_bonus = params[:school_bonus]      @old_family_bonus = params[:family_bonus]      @selected_school.bonus_attr == @selected_family.bonus_attr ? @increase_val = 4 : @increase_val = 3      respond_to do |format|        format.js      end    end  

That`s all I think that is relevant to this case.

Caching a lot of dynamic pages on Rails [on hold]

Posted: 06 May 2016 08:01 PM PDT

This is a question on how to handle caching on a lot of dynamic pages generated by a Rails application. It isn't exactly limited to programming but is more about how to structure an application.

I have a product catalog site that has millions of dynamic pages (10m+) generated per category. The page load itself of each of these pages is acceptable (not that fast but not that slow either). The problem is these pages introduce a huge amount of DB load that cripples my database (MySQL). Some hits come from actual users, most hits come from search engine bots.

What I need:

  1. Reduce DB load of these pages
  2. Refresh these pages every other day
  3. Do not hit the DB hard when refreshing
  4. I prefer a cheap and simple solution

So here are some solutions on the top of my head:

  1. Cache the page

    • Web server caching - Cache it on web server and don't let it hit the app server. This would need using JS (ajax) to handle app level data (authentication).
    • Memcached/Redis - Store products on a KV store. This would need a huge amount of memory and would cost a lot.
    • Cache on MySQL - Store generated pages on a table. I don't like this solution and I don't see it being different from storing blobs on DB. But using this would allow me to programatically update the cache (cron, delayed jobs, etc) that wouldn't cause too much load when I try to update the pages.

    • I have 2 problems with caching the page. First is that caching the pages would take up huge amounts of memory/disk space. Second is that I need these pages to refresh every other day at least and when a new product is added, I need to update an average of 50k pages. I would also need a smart way to re-cache these pages and not introduce DB load issues in the process.

  2. Separate database for these pages

    • I'm thinking if it would be worth it to read from a separate database instead, so it would isolate this from my main database. The biggest advantage of this is I won't need to regularly update the cache.

Currently, I'm leaning towards just caching the page on MySQL as it is the cheapest and I already have MySQL set up, so it would be the simplest. My worry is that this table would introduce complexity and would be hard to maintain over time.

Are there more solutions I didn't think of? What do you think of each solution? Please let me know, thanks!

Clicking on links in emails auto-fill the date, rails

Posted: 06 May 2016 07:56 PM PDT

So right now I am completely stumped, I am trying to set up an action mailer in a ruby on rails app to autofill the date on my check in form with the date of the missing check in, and have no idea where to start.

    <!DOCTYPE html>      <html>      <head>       <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />       </head>   <body>  <p>    Psssstt! Remember to <%= link_to "check-in for #{@friendly_date}", new_check_in_url %>  </p>  <p> --Team Capacitor  </p>  

Above is the original email where we have the date, which already leads to the check in form, I just need to know how to autofill the date picker with the @friendly_date once the link is clicked.

I appreciate any help I can get.

Thanks

No comments:

Post a Comment