vendredi 31 juillet 2015

Bower in Rails app before bower-rails

Inherited a project that has has a rather sparse .bowerrc file and a .bower.json full of dependencies at its root. There is no bower-rails in the Gemfile and thus no Bower Rake tasks.

I'm tempted just to drop in the bower-rails gem and move along but curious how the previous team might have interacted with Bower without bower-rails?

Also, I assume .bower.json pre-dates Bowerfile? OK to migrate .bower.json -> Bowerfile or is there a reason not to?

Seemingly simple questions but Bower 'just works' so I don't tend to fiddle with it much.

Convert mysql to postgres and retain default value

I have a MySQL database that I wish to convert into Postgres. One issue I encountered is to convert tinyint(1) (synonym to boolean) columns into "true" boolean and retain the default value of the MySQL column which can be either 0 or 1 but in Postgres the respective values are true or false. The SQL I'm trying:

ALTER TABLE "payments" ALTER COLUMN "is_automatic" TYPE boolean USING CAST("is_automatic" as boolean);

The error message:

ERROR:  default for column "is_automatic" cannot be cast automatically to type boolean

I would think it would be possible to cast this value somehow. Is this possible to do or do I have to manually add this to the migration script?

Breaking a parameter and save the items separately

I need to save items separately coming from a form of a text field, but my code is saving these items duplicate form.

My controller

def create

  @answer_option = AnswerOption.break_options(answer_option_params)
  @answer_option = AnswerOption.new(answer_option_params)

  respond_to do |format|
    if @answer_option.save
      format.html { redirect_to @answer_option, notice: 'Answer option was successfully created.' }
      format.json { render :show, status: :created, location: @answer_option }
    else
      format.html { render :new }
      format.json { render json: @answer_option.errors, status: :unprocessable_entity }
    end
  end
end

My model

class AnswerOption < ActiveRecord::Base
  belongs_to :question

  def self.break_options(var)
    ugly_answers = var[:content].split /[\r\n]+/
    ugly_answers.each do |answer|
      AnswerOption.create!(content: answer)
    end
  end

end

Thanks!

undefined method for Questions

I am getting the error undefined method `questions' for nil:NilClass when viewing different profiles. I am not seeing why this is an undefined method. Anyone have a clue what I did not do correct?

Logs:

NoMethodError (undefined method `questions' for nil:NilClass): 
app/controllers/users_controller.rb:80:in `show' 

Users Controller:

 def show
    @question = @user.questions.where("answer is not null").order("created_at DESC").page(params[:page]).per_page(3)

Questions Model:

  attr_accessible :answer, :question, :sender_id, :recipient_id, :conversation_id, :twitter, :facebook
  belongs_to :user

  belongs_to :sender,:class_name => 'User',:foreign_key => 'sender_id'

  belongs_to :recipient,:class_name => 'User',:foreign_key => 'recipient_id'

  belongs_to :message

  belongs_to :conversation

  def self.total_answer
      where('answer IS NOT NULL').count
    end

    def self.total_answer_cancelled
        where('answer IS NULL').count
      end

      def self.total_male
        count_of_males = Question.joins(:sender).where(users: {gender: 'male'}).uniq.count
      end

      def self.total_female
        count_of_males = Question.joins(:sender).where(users: {gender: 'female'}).uniq.count
      end

Questions Controller:

  def show
      @question = Question.find(params[:id])
      @questions = Question.order("created_at DESC")
      respond_with(@questions)
    end

    def create
      @question = Question.new(params[:question])
      if @question.save
        @message = current_user.send_message(@question.recipient, @question.question, "You have a question from #{@current_user}") 
        @question.update(:conversation_id => @message.notification.conversation.id)
        render :json => {:notice => 'Your question was saved successfully. Thanks!' }
      else
        render :new, alert: 'Sorry. There was a problem saving your question.'
      end
    end

Rails responding to different formats with AJAX request

I'm trying to understand AJAX requests in Rails. I have a form that I currently submit using remote: true. I want to respond with an HTML redirect if the request is successful, and run an error message with Javascript if it is unsuccessful. However, no matter what the outcome is, the request seems to expect a .html as the return.

respond_to do |format|
  if conversation
    format.html { redirect_to(conversation_path(conversation)) }
  else
    format.js
  end
end

This is called after I save the conversation call on AJAX. On a successful save, the path is correctly rendered. But on an unsuccessful save, it expects the .html and throws an error. How do I accept .js as a response? My goal is to just pop up an error if the call is unsuccessful

Edit: My form_fro:

            <%= form_for :conversation, url: :conversations, html: { class: "conversation-form" } do |f| %>

Rails - Active Record: Find all records which have a count on has_many association with certain attributes

A user has many identities.

class User < ActiveRecord::Base
    has_many :identities
end

class Identity < ActiveRecord::Base
    belongs_to :user
end

An identity has an a confirmed:boolean column. I'd like to query all users that have an only ONE identity. This identity must also be confirmed false.

I've tried this

User.joins(:identities).group("users.id").having( 'count(user_id) = 1').where(identities: { confirmed: false })

But this returns users with one identity confirmed:false but they could also have additional identities if they are confirmed true. I only want users with only one identity confirmed:false and no additional identities that are have confirmed attribute as true.

I've also tried this but obviously it's slow and I'm looking for the right SQL to just do this in one query.

  def self.new_users
    users = User.joins(:identities).where(identities: { confirmed: false })
    users.select { |user| user.identities.count == 1 }
  end

Apologies upfront if this was already answered but I could not find a similar post.

Limit to nested forms with accepts_nested_attributes_for

I have a registration form that creates a User and, via nested forms, needs to work as follows:

Users have Events

Events have EventSessions

EventSessions have a Location

Rails allows me to update as far down as EventSessions because the User model contains: has_many :little_class_sessions, through: :little_classes.

I'm unable to save to Location because it's nested under EventSessions. That's one level too deep for rails, and it throws an exception.

What would be the most correct way to create the Location and update the EventSession with the location_id? Inside the UserController?

Background worker prevents photos from uploading

I have the carrier wave gem installed and I added a background worker to it (carrierwave_backgrounder gem`). The issue is now when I upload a photo it shows an empty box where the photo should be.

Photos model:

  mount_uploader :image, ImageUploader
  process_in_background :image
  store_in_background :image

image_uploader.rb:

  include CarrierWave::ImageOptimizer
  include CarrierWave::MiniMagick
  include ::CarrierWave::Backgrounder::Delay

/initializers/carrierwave_backgrounder.rb:

CarrierWave::Backgrounder.configure do |c|

  c.backend :sidekiq, queue: :carrierwave
end

Migration:

class AddTempToUser < ActiveRecord::Migration
  def change
    add_column :users, :avatar_tmp, :string
  end

Photos controller:

 def create
    @photo = Photo.create(photo_params)
    @photo.user = current_user
    if @photo.valid? and @photo.save!
      flash[:notice] = "Successfully created photos."
      redirect_to :back
    else
      flash[:notice] = @photo.errors.messages[:base].first
      render :action => 'new'
    end
  end

Server logs:

Jul 31 17:28:07 areyoutaken app/web.1:  Processing by PhotosController#create as JS 
Jul 31 17:28:07 areyoutaken app/web.1:  Processing by PhotosController#create as JS 
Jul 31 17:28:07 areyoutaken app/web.1:    Parameters: {"utf8"=>"✓", "authenticity_token"=>"xhE8IGs/FLF+cJvMWMJeC5sUFkGk76Xe6SoWzT8v1Pg=", "photo"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007f7e80662960 @tempfile=#<Tempfile:/tmp/RackMultipart20150801-3-eiq7px>, @original_filename="love.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"photo[image]\"; filename=\"love.jpg\"\r\nContent-Type: image/jpeg\r\n">}} 
Jul 31 17:28:07 areyoutaken app/web.1:    Parameters: {"utf8"=>"✓", "authenticity_token"=>"xhE8IGs/FLF+cJvMWMJeC5sUFkGk76Xe6SoWzT8v1Pg=", "photo"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007f7e80662960 @tempfile=#<Tempfile:/tmp/RackMultipart20150801-3-eiq7px>, @original_filename="love.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"photo[image]\"; filename=\"love.jpg\"\r\nContent-Type: image/jpeg\r\n">}} 

Trying to "redirect_to :back" after logging in

I'm trying to redirect to the previous page after a user logs in. I am using a bootstrap modal for login/register forms but if someone doesn't have JS enabled on their browser and are taken to the '/login' page, I want to make sure they are redirected to the root url. I know current_page? does not work with POST requests.

I've tried tons of things so the following code is redirecting correctly from the '/login' page to the root url but I am not being redirected to ':back' when logging in using the bootstrap modal.

This is from SessionsController: (PS- I have sessions#new/sessions#create as /login in routes)

def create
    user = User.find_by(email: params[:email]) 
    if user && user.authenticate(params[:password])
        session[:user_id] = user.id

            if request.path === '/login'
                redirect_to '/'
            else
                redirect_to :back
            end

            flash[:success] = "Logged in."

    else
        flash.now[:danger] = "Email and password did not match. Please try again."
        render :new
    end
end

def destroy
    session[:user_id] = nil
    flash[:success] = "Logged out."
    redirect_to '/'
end

Routes.rb:

Rails.application.routes.draw do

root to: 'home#home'

resources :users

get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
get '/logout', to: 'sessions#destroy'

end

How can I refresh the cache of model manually in rake file

How can I refresh the cache of model manually

I can cached pages with fragment,

and refresh it in outside rake task

But I have no idea how to refresh the cache inside the controller for fetching data from DB.

How could I refresh the cache in Rake file

def get_max_and_min_routes(airline_name, from, to)
  Rails.cache.fetch("I_AM_CACHE_KEY") do
    FETCH_FROM_DB
  end
end

rake file

action_controller = ActionController::Base.new
action_controller.expire_fragment("body_header")
action_controller.expire_fragment("index")
action_controller.expire_fragment("welcome_index_controller")
action_controller.expire_fragment("footer")

index.haml

- cache("index", skip_digest: true) do
  = render "historical_prices"
= render "common/recently_changed_prices"

RSpec - ActiveRecord::RecordNotFound when testing templates

I'm trying to test that my templates are rendering but can't seem to figure out why its not registering the ID of my stubbed instance. What do I have to do to get a correct path?

describe RestaurantsController do
  let(:restaurant) { FactoryGirl.build_stubbed(:restaurant) }

  describe "GET #show" do
    before { get :show, id: restaurant.id }
    it { should render_template('show') }
  end
end

Error:

1) RestaurantsController GET #show 
     Failure/Error: before { get :show, id: restaurant.id }
     ActiveRecord::RecordNotFound:
       Couldn't find Restaurant

Dokku push error

After several try to push an app to a dokku instance . i keep receiving this error.I've already search both github and stackoverflow for similar issues but none of them resolve it.I have check my css folders and files for any issue .Unable to pinpoint where the error coming from. If anybody have an idea to resolve it . please share.

 NoMethodError: undefined method `[]' for nil:NilClass                                                                                                                                 
       (in /tmp/build/app/assets/stylesheets/application.css)                                                                                                                                
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sprockets-2.12.4/lib/sprockets/sass_functions.rb:63:in `sprockets_context'                                                                   
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sprockets-2.12.4/lib/sprockets/sass_functions.rb:14:in `image_path'                                                                          
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/funcall.rb:113:in `_perform'                                                                                     
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/node.rb:40:in `perform'                                                                                          
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/list.rb:71:in `block in _perform'                                                                                
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/list.rb:71:in `map'                                                                                              
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/list.rb:71:in `_perform'                                                                                         
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/node.rb:40:in `perform'                                                                                          
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:298:in `visit_prop'                                                                            
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:37:in `visit'                                                                                     
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:100:in `visit'                                                                                 
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:53:in `block in visit_children'                                                                   
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:53:in `map'                                                                                       
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:53:in `visit_children'                                                                            
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:109:in `block in visit_children'                                                               
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:121:in `with_environment'                                                                      
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:108:in `visit_children'                                                                        
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:37:in `block in visit'                                                                            
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:320:in `visit_rule'                                                                            
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:37:in `visit'                                                                                     
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:100:in `visit'                                                                                 
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:53:in `block in visit_children'                                                                   
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:53:in `map' 

ActionController::ParameterMissing in SubjectsController#update

I'm a beginner in RoR. I'm taking the course in lynda.com by Kevin. I'm doing the CRUD in RoR. When I do delete operation it is showing the error

ActionController::ParameterMissing in SubjectsController#update

param is missing or the value is empty: subject

subjects_controller.rb

class SubjectsController < ApplicationController

def index
    render('index')
end

def list
    @subjects = Subject.order("subjects.position ASC")
end

def show
    @subject = Subject.find(params[:id])
end

def new
    @subject = Subject.new(:name => 'username')
end

def create
    @subject = Subject.new(params.require(:subject).permit(:name, :position, :visible))
    if @subject.save
        redirect_to(:action => 'list')
    else
        render('new')
    end
end

def edit
    @subject = Subject.find(params[:id])
end

def update
    @subject = Subject.find(params[:id])
    if @subject.update(subject_params)
        redirect_to(:action => 'show', :id => @subject.id)
    else
        render('edit')
    end
end

def delete
    @subject = Subject.find(params[:id])
end

def destroy
    @subject = Subject.find(params[:id])
    @subject.destroy
    redirect_to(:action => 'list')
end

private
def subject_params
  params.require(:subject).permit(:id, :name, :position, :visible)
end

The highlighted lines of error are

if @subject.update(subject_params)

and

 params.require(:subject).permit(:id, :name, :position, :visible)

delere.html.erb

<%= link_to("<<Back to List", {:action => 'list'}, :class => 'back-link') %>
<%= form_for(:subject, :url => {:action => 'destroy', :id => @subject.id}) do |f| -%>
    <p>Are you sure that you want to delete this subject permanently?</p>
    <p class="reference-name"><%= @subject.name %></p>

    <div class="form-buttons">
        <%= submit_tag("Delete Subject") %>
    </div>
<% end %>

edit.html.erb

<%= link_to("<<Back to List", {:action => 'list'}, :class => 'back-link') %>

<%= form_for(:subject, :url => {:action => 'update', :id => @subject.id}) do |f| %>

    <table summary="Subject from fields">
        <tr>
            <th>Name</th>
            <td><%= f.text_field(:name) %></td>
        </tr>
        <tr>
            <th>Position</th>
            <td><%= f.text_field(:position) %></td>
        </tr>
        <tr>
            <th>Visible</th>
            <td><%= f.text_field(:visible) %></td>
        </tr>
    </table>

    <div class="form-buttons">
        <%= submit_tag("Update Subject") %>
    </div>
<% end %>

Any ideas? Thank you in advance.

Rails routing with REST api and mobile client

Hello I have a standard rails app with some endpoints that serve json format, ad I have the contraint of having them with api-dev, this works great locally but unfortunatly does not play along very well with a mobile client that needs to fetch it through the network but if I try to point to specific ipaddress of course it won't load because the constraint requires a subdomain (api-dev),

Is it possible in rails to have the constraint and by default allow the endpoint to be hit?. BTW I also have a webclient in the same project and it has a subdomain constraint of dashboard.

Setitng custom field values doesn't work with Paranoia

I have been trying to set up Paranoia with my project. I have a deleted_at column and another column status which is equal to 2 when it's deleted.

Model Class

class Account < ActiveRecord::Base

  acts_as_paranoid column: :status, sentinel_value: 1

  def paranoia_restore_attributes
    {
      deleted_at: nil,
      status: 1
    }
  end

  def paranoia_destroy_attributes
    {
      deleted_at: current_time_from_proper_timezone,
      status: 2
    }
  end 
end

But when I perform destroy or restore, it doesn't seem to change the status value.

How many rails instances does delayed job initialize if running multiple pools

I'm running Delayed Job with the pool option like:

bundle exec bin/delayed_job -m --pool=queue1 --pool=queue2 start

Will this spawn one OR multiple rails environments? (ie: will it spawn one environment for all the pools or will every pool gets its own rails environment)?

When testing locally it seemed to only spawn one rails environment for all the pools.

But I want to confirm this 100% (esp on production).

I tried using commands like these to see what the DJ processes were actually pointing to:

ps aux, lsof, pstree

Anyone know for sure how this works, or any easy way to find out? I started digging through the source code but figured someone prob knows a quicker way.

Thanks!

Auto-association cascading

In my Rails learning this site has been very fruitful. My question has to do with Rails + PostgreSQL:

I learned the PostgreSQL is to make self-association and plan to use it in the following situation;

1- I am doing a forum that has categories.

2- When the category_id be |= (different) null / NILL mean he is in the category that was made to the association.

And so on may have several subcategories cascade, and I intend to do the same thing with topics and replies of topics.

I wonder how I associate it in the model and how to do a search in cascade form in the rails?

Thanks,

ActiveRecord::AssociationTypeMismatch in ProductosController#create

Im trying to create a new product (producto in spanish) which belongs to a category (categoria). When i submit the error shows:

ActiveRecord::AssociationTypeMismatch in ProductosController#create
Categoria(#47681880) expected, got String(#4043652)

Extracted source (around line #10):
def create
 @producto = Producto.new(params_producto)

 if @producto.save
redirect_to categorias_path, :notice => "se ha creado un producto"

My product controller:

class ProductosController < ApplicationController
 def new
  @producto = Producto.new
  @categoria = Categoria.all
 end
 def index
    @producto = Producto.all
 end
 def create
     @producto = Producto.new(params_producto)

     if @producto.save
         redirect_to categorias_path, :notice => "se ha creado un producto"
     else
      render 'new'
     end
 end
  def params_producto
   params.require(:producto).permit!
  end
def show
 @producto = Producto.find(params[:id])
end
end

products model

class Producto < ActiveRecord::Base
  belongs_to :categoria
  validates :nombre, uniqueness: { message: "ya existe"}

end

new html:

<%= form_for :producto, url: productos_path do |f| %>
  <% if @producto.errors.any? %>
   <div id="error_explanation">
     <ul>
    <% @producto.errors.full_messages.each do |msg| %>
      <li>El <%= msg %></li>
    <% end %>
  </ul>
  </div>
 <% end %>
 <p>
   <%= f.label :nombre %><br>
    <%= f.text_field :nombre %>
 </p>

 <p>
    <%= f.label :categoria %><br>
     <%= f.select :categoria_id, Categoria.all.collect {|x| [x.nombre, x.id]}, { :include_blank => "Select one" } %>
 </p>

 <p>
   <%= f.submit %>
  </p>
 <% end %>

Category model:

class Categoria < ActiveRecord::Base
  has_many :productos

end

im using rails 4.1

Is it possible to execute a method after sending a response back to the browser in Rails?

I'm trying to run an action after I send a response back to the client in Rails. Is it possible to do this without background workers or creating new threads?

I looked into the after_filter callback, but it seems like this only lets you execute code before you render the view / response.

Thanks

Is it considered poor practice to use the same view for creation and editing in an MVC application

I'm writing a web application which allows users to create (and then later, edit) blog-like text posts. Because the page for creating it will be identical to the page for editing it, I'm tempted to use the same page for both.

It seems to me like this would be a good example of DRY(Don't Repeat Yourself). However, using that same page and with some modifications and auto-populations seems a bit dirty and difficult to maintain (e.g. I add a control or feature to the editing page and now I have to make sure that it doesn't show on the creation page or get broken by any javascript I may have written.

This Question asked something similar but all the answers spoke more about HOW to implement it, not whether it was good, maintainable practice

rails 4 refresh only specific div with ajax

this is my second question on stackoverfloy. If i did a mistake, i'm sorry, i'm really new to here. So please be gentle.

I just learned RoR and i want to build a rails app for my GF's birthday. I have 2 models and 2 controllers. One of for image and the other one for the text.

I did randomize they in my images controller's index function to show in index.html And placed a button for refreshing the page so image and text randomize again.

But i want to add background music to this. So i need to use ajax for button to keep music from restarting over again. I did a research and tried many solutions. But i cant succeed.

Here is my controller:

class ImagesController < ApplicationController


    def index
      @randimg = Image.order("RANDOM()").first
      @randtext = Text.order("RANDOM()").first

      respond_to do |format|
        format.js 
        format.html
      end

Here is my images index.html.erb:

<!DOCTYPE html>
<html lang="tr">
<head>
  <title>2 Ağustos 1993</title>
  <meta charset="utf-8">
  <link href='http://ift.tt/1nio39n' rel='stylesheet' type='text/css'>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <%= javascript_include_tag "application" %>
</head>

<body>
  <div class="container">
    <%= render 'text' %>
    <%= render 'image' %>
  </div>
  <center>
    <%= link_to "İyi ki doğdun bebeğim, seni çok seviyorum",
              {:controller => 'images', :action => 'index'},
              :remote => true,
              class:'btn btn-info' %>
  </center>

  <audio autoplay="true" loop="true" preload="">
 <source src="bg.mp3" type="audio/mpeg"></source>
 Your browser does not support the audio element.
</audio>
</body>
</html>

And as far as i know i need to specify index.js.erb to use ajax, here it is;

$("#container").html("<%= j render :partial => 'image' %>")

I know my app is not the best or cleanest. This is my first app on rails. Thanks in advance.

PS: English is not my native language, i'm sorry if i type something mistaken.

sessionsController API not invoked when the login credentials are wrong

This is my sessionController API above the devise SessionController

class Api::SessionsController < Devise::SessionsController
skip_before_filter :verify_authenticity_token,
:if => Proc.new { |c| c.request.format =='application/json' }
respond_to :json
def create
warden.authenticate!(:scope => resource_name, :recall => "Api::SessionsController#failure")
render :status => 200,
       :json => { :success => true,
                  :info => "Logged in",
                  :data => {} } # { :auth_token => current_user.authentication_token } }
end

def failure
render :status => 401,
       :json => { :success => false,
                  :info => "Login Failed",
                  :data => {} } end
end

When the login credentials are right, the create function is invoked and it returns the right response. When login credentials are wrong the failure function is not invoked while its not going into the sessionController API but Devise::SessionsController instead and return the response in the Devise::SessionsController. Anyone have any ideas? Thanks alot!

Rails Problems with IE

I've got several problems with a Rails 4.2.1 and Ruby 2.1 application in actual IE. If I save something to a database and do a redirect, the values are saved twice in the database.

Does anyone have this as well?

Rails form_for uploads picture but file_field_tag does not

This code successfully uploads and image as part of a Notice, using a form builder:

<%= form_for(@notice, html: { multipart: true }) do |f| %>
  <%= hidden_field_tag :callsign,  @notice.character.callsign %>
  <%= f.hidden_field :commentee_id, value: nil %>
  <%= f.hidden_field :latitude,  id: "notice_latitude"  %>
  <%= f.hidden_field :longitude, id: "notice_longitude" %>
  <div class="field">
    <%= f.text_area :content, id: "dropfield", placeholder: "What's going on here?" %>
  </div>

  <span class="picture">
    <%= f.file_field :picture, accept: 'image/jpeg,image/gif,image/png' %>
  </span>

  <%= f.submit "Drop", class: "btn btn-success", onclick: "return validateDropForm();" %>
  <button type="button" class="btn btn-danger" id="cancel_drop">Cancel</button>
<% end %>

But using a file_field_tag fails:

<%= form_tag( {controller: "notices", action: "create"}, method: "post", class: "comment_form", html: { multipart: true } ) do %>
  <%= hidden_field_tag :callsign, @character.callsign %>
  <%= hidden_field_tag "notice[supernotice][commentee_id]", notice.id %>
  <%= hidden_field_tag "notice[latitude]",  notice.latitude,  id: "comment_notice_latitude"  %>
  <%= hidden_field_tag "notice[longitude]", notice.longitude, id: "comment_notice_longitude" %>
  <%= text_area_tag "notice[content]", '', rows: 1, id: "commentField-#{notice.id}", class: "comment_area" %>
  <%= button_tag( type: 'submit', name: nil, title: 'Post',
                  class: 'btn btn-default btn-xs comment_submit',
                  onclick: "return validateCommentForm('#commentField-#{notice.id}');" ) do %>
    <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
  <% end %>

  <%= file_field_tag "notice[picture]", accept: 'image/jpeg,image/gif,image/png',
                                        class: "file_field", title: "Upload picture"  %>

  <%= button_to "Upload file", class: 'btn btn-default btn-xs uploadbutton' do %>
    <span class="glyphicon glyphicon-upload" aria-hidden="true"></span>
  <% end %>
<% end %>

The file_field_tag code successfully opens an "open file" window so you can select the file you want to upload, and upon submission the notice is successfully created, the :content is present, but the picture is not included. The logs show that while the picture is initially included in the request, it somehow has become nil upon INSERT INTO the database:

Started POST "/notices" for ::1 at 2015-07-31 22:21:57 +0100
Processing by NoticesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"SnKZ...lg==",
"callsign"=>"bazzer",
"notice"=>{"supernotice"=>{"commentee_id"=>"15022"},
"latitude"=>"54.0239066230473",
"longitude"=>"-1.02996826171875",
"content"=>"This isn't going to work!",
"picture"=>"pic1.jpeg"}}
.
.
SQL (5.9ms)  INSERT INTO "notices" ("content", "picture", "latitude", "longitude", "character_id", "created_at", "updated_at")
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING "id"  [["content", "This isn't going to work!"], 
["picture", nil], ["latitude", 54.0239066230473],
["longitude", -1.02996826171875],
["character_id", 1], 
["created_at", "2015-07-31 21:21:57.451695"],
["updated_at", "2015-07-31 21:21:57.451695"]]

Using file_field instead of file_field_tag makes no difference.

What is wrong with the code? How do I get the file_field_tag to successfully upload a picture?

Trying to create log in form with Parse in Rails

so im trying to create a login form for Parse in rails using gem parse-ruby-client and this is what i got so far, i know i have some routing issue i need help with.

I have two controllers and two views.

this is the first set. (login_controller and index.html.erb)

heres what i got:

login_controller.rb:

class LoginController < ApplicationController
  def index
    user = Parse::User.authenticate(params[:user][:username],params[:user][:password] )
  end
end

index.html.erb:

<% @page_title = "Log in" %>
<div class="Log_in_Form">
  <h4><center>Log in with your existing "app_name" account</center></h4>
  <%= form_for(:user, :url => {:controller => 'login', :action => 'index'}) do |f| %>
    <center><p> Username:</br> <%= f.text_field :username%> </p></center>
    <center><p> Password:</br> <%= f.password_field :password%></p></center>
    <center><h4><%= f.submit :Login %></h4></center>
  <% end %>
</div>

routes.rb

Rails.application.routes.draw do
  get 'welcome/index'

  root 'login#index'

end

basically i want to be able to input username and password and be directed to the next view being logged in successfully.

Routing concerns defining different param for resources

Recently I got to know about rails concerns in routes from this discussion How to have same routes with and without namespace - rails 4. Now in my application I have routes like this:

namespace :admin do
  resources :photos
  resources :businesses
  resources :projects
  resources :quotes
end
resources :photos, param: 'slug'
resources :businesses, param: 'slug' do
  resources :projects, param: 'slug' #As I need both the url one inside business and one outside
end
resources :projects, param: 'slug'
resources :quotes, param: 'slug'

And there are many more resources which are repeating as I needed them. I know about concerns how to implement them. With the concerns I can do it like this:

concern :shared_resources do
  resources :photos
  resources :businesses
  resources :projects
  resources :quotes
end
namespace :admin do
  concerns :shared_resources
end
concerns :shared_resources

but how can I give different param each time in the concerns? I tried doing it like this:

concerns :shared_resources, param: 'slug'

But this brings no change in the routes. And if I add:

resources :photos, param: 'slug'

Then it will add to both the routes slug instead of id. But in admin side I need id and in front end I need slug. So are there any options to pass this in the concerns so to DRY up the code.

Ruby on Rails persistently store Hash from CSV

I have a ruby script written which takes a CSV file and converts the input into a hash:

Culper = File.open('.\CulperCSV.csv')

culper_hash = {}

# set up culper code hash from provided CSV
CSV.foreach(Culper) do |row|
    number, word = row
    culper_hash[word] = number
end

and I am trying to make a Rails app using the script.

My question: How do I store the Hash persistently (or the CSV data so I can build the hash) so that I can minimize load times?

My thoughts:

1) Load the CSV data into a database (seed it) and each time I get a visitor on my site, do the above assignment into a hash but from the db. (not sure how to do this but I can research it).

or

2) Load the complete hash into the database (I think I would have to serialize it?) so that I can do just one fetch from the db and have the hash ready to go.

I am very new to building apps, especially in Rails so please ask questions if what I am trying to do doesn't make sense.

Cannot access local postgreSQL heroku, node.js

Set up a node.js app with postgreSQL db, all works in production environment.

I have used the CLI heroku pg:pull ... which was successful. Am running postgres 9.4.X locally, but on starting my application locally (foreman start) I am getting an error: "Error error: relation "test_table" does not exist". I have followed instructions here: http://ift.tt/1qkNZiD but still I cannot seem to access my DB when running locally.

bash_profile:

export PATH="/usr/local/heroku/bin:$PATH"
export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/9.4/bin
export PATH="/Applications/http://ift.tt/1IuFVVc"

Console error log:

15:39:48 web.1 | started with pid 18779
15:39:48 web.1 | Node app is running on port 5000
15:39:52 web.1 | { [error: relation "test_table" does not exist]
15:39:52 web.1 | name: 'error',
15:39:52 web.1 | length: 101,
15:39:52 web.1 | severity: 'ERROR',
15:39:52 web.1 | code: '42P01',
15:39:52 web.1 | detail: undefined,
15:39:52 web.1 | hint: undefined,
15:39:52 web.1 | position: '15',
15:39:52 web.1 | internalPosition: undefined,
15:39:52 web.1 | internalQuery: undefined,
15:39:52 web.1 | where: undefined,
15:39:52 web.1 | schema: undefined,
15:39:52 web.1 | table: undefined,
15:39:52 web.1 | column: undefined,
15:39:52 web.1 | dataType: undefined,
15:39:52 web.1 | constraint: undefined,
15:39:52 web.1 | file: 'parse_relation.c',
15:39:52 web.1 | line: '986',
15:39:52 web.1 | routine: 'parserOpenTable' }

How do I test validations in Rubymine?

Im new to learning Rails and am using Rubymine. Im going through the book RailsSpace and have a question. We created a user model and then created all these validations for when we create new users and it now says to test our validations... However I am not quite sure how to do that. It shows me the code but Im not sure where in Rubymine I can go to test the user validations we made. Help :)

Here's the code it shows the book. From what I understand I need to try and create a new user and give it a username, email, and password... And then it's giving errors on the validations. But where do I create this new user and enter the username, password, and email?

reload!

user = User.new( :screen_name => "me",

?> :password => "a"

?> :email => " ")

=> #"me", "password"=>"a", "email"=>""}>

user.save

=> false

user.errors.on(:screen_name)

=>["is to short (minimum is 4 charaters)", "has already been taken"]

Thanks! C

Rails with thin and ssl: http request not auto-redirected to https

Recently I wanted to secure my rails 4.2.1 app with https the easiest way. I found this question as well as this answer about WEBrick+SSL, both referencing to this post which is unfortunately not reachable any more. Then I found this answer recommending to use thin instead (naming other advantages of using thin). Then I followed this step-by-step guide, finally running thin start --ssl --ssl-key-file .ssl/key.pem --ssl-cert-file .ssl/cert.pem -e production with self-signed certificate. My config/environments/production.rb contains config.force_ssl = true.

Now I would like to access the web normally by typing example.com expecting to be automatically redirected to https://example.com but this does not happen. Typing looong https://example.com works fine. Here is a 2-year-old question with similar issue but any answer doesn't work either and something could have also changed since then.

How can I make it work? Or is there any different recent but simple enough way to start using ssl with rails? Thanks!

Rails correct way to submit nested parameters in form

This code successfully creates a new Notice, as intended:

In the submit form:

<%= hidden_field_tag "notice[supernotice][commentee_id]", notice.id %>

In the notices_controller.rb:

def create
  @character = Character.find_by(callsign: params[:callsign])
  @notice = @character.notices.build(notice_params)
  if @notice.save
    if !params[:notice][:supernotice][:commentee_id].nil?
      @notice.create_comment(params[:notice][:supernotice][:commentee_id]) # hits the create_comment method in notice.rb
    end
  end

def notice_params
  params.require(:notice).permit(:content, :picture, :latitude, :longitude, supernotice_attributes: [:commentee_id] )
end

Class notice.rb:

has_one :supernotice, through: :active_comment_relationship, source: :commentee
accepts_nested_attributes_for :supernotice

def create_comment(other_notice_id)
  create_active_comment_relationship(commentee_id: other_notice_id)
end

However, the logs show the error: Unpermitted parameter: supernotice. How do I get rid of this error? What is wrong with the way I am submitting the nested parameter?

Ruby on Rails 3: Streaming data and catching exception

I'm streaming data using the following approach:

self.response_body = Enumerator.new do |y|
    10_000_000.times do |i|
        y << "This is line #{i}\n"
    end
end

I'm trying to catch any exception generated inside Enumerator and present something nicer to the user. Right now, the app is presenting an ugly error page from Torquebox. e.g.

Torquebox/Jboss error page.

I tried rescue and redirect_to and many other ways to catch the exception (including add a middleware class for handling exceptions). Any help would be appreciated!.

(The app is made under jruby v1.7.19 and torquebox v3.1.1)

Rails active record WHERE EXISTS query

I have an SQL query that returns what I need, but I'm having trouble converting this into an active record query the "Rails way".

My SQL query is:

SELECT * from trips 
WHERE trips.title LIKE "%Thailand%"
AND EXISTS (SELECT * from places WHERE places.trip_id = trips.id AND places.name LIKE "%Bangkok%")
AND EXISTS (SELECT * from places WHERE places.trip_id = trips.id AND places.name LIKE "%Phuket%")

I'm trying something like this using Rails:

@trips=Trip.where("trips.title LIKE ?", "%Thailand%")
@trips=@trips.includes(:places).where(("places.name LIKE ?","%Bangkok%").exists?) => true, ("places.name LIKE ?","%Phuket%").exists?) => true)

But it doesn't seem to work and i'm stumped as to what to try.

Rails Date Formate

When I do this:

DateTime.now.to_s

I Got: 2015-07-31T22:22:05+02:00

But I need it in this format:

2015-07-31 22:22:05

How can I format it this way?

Broken images/css in production mode with Rails 4

I'm running a Rails 4 application in production mode...in Windows 8.1... For some reason y have broken images and css in production mode. Since there is no Passenger gem in Windows, I have to use Apache config to redirect or reverse proxy to Thin:

<VirtualHost *:8888>
    ServerAdmin webmaster@example.com
    ServerName Depot
    #ServerAlias 

    DocumentRoot "c:/my_directory_tree/depot" 

    <Directory "C:/my_directory_tree/depot">
        Require all granted
        Options -MultiViews
    </Directory>

    ProxyPass /depot http://balancerdepot_cluster/
    ProxyPassReverse /depot http://balancerdepot_cluster/
    ProxyPreserveHost On

    <Proxy http://balancerdepot_cluster>
        BalancerMember http://ift.tt/1OTx1pQ
    </Proxy>

    #ErrorLog  "|C:/Webserver/Apache/bin/rotatelogs.exe logs/http://ift.tt/1JBdB8Z 86400" 
    #CustomLog "|C:/Webserver/Apache/bin/rotatelogs.exe logs/http://ift.tt/1OTx1pS 86400" 

combined

</VirtualHost>

And run my application with:

thin -p 3000 -e production --prefix /depot start -p 3001

I already precompiled my assets, but didn't work either.

rake assets:precompile

Why I'm running in production mode my app? Well... before implementing in a real production server, I need to know how to implement this application in Windows server...

How can I simulate password autofilling in my integration test?

On my password change page I have the new password field named password, and the current password field named current_password so that password managers will pick up on the change and prompt to save your new password. (Also it's default devise behavior)

However if a user doesn't want to change their password, I have them leave the new password field blank (again devise default behavior), but password managers will often autofill this field with the current password.

That's not a problem, I just use js to clear the field if the value was entered automatically. But I'd like to test this, and can't figure out how to get capybara (webkit driver) to fill in the field in a way that doesn't get interpreted as manual by js. (ie doesn't focus the field)

Currently I wipe the value (once) if the field wasn't focused before the value was entered. That way there's no race conditions and the field becomes intelligible to use if the user wants to use it (focuses the field).

Rails 4 form and listing on same page, correct format responses

The goal is to create, edit and destroy model category on index page. I am able to save the model but I can not refresh the listing. I have read many similar examples, its confusing.

This is what I have:

At views/categories/index.html.erb

<!-- Full expand -->
<div class="row mt-20">
        <div class="well-basic">
            <div class="col-xs-8">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Content</th>
                            <th>Actions</th>
                            <th colspan="3"></th>
                        </tr>
                    </thead>

                    <tbody>
                        <% @categories.each do |category| %>
                        <tr>
                            <td><%= category.content %></td>
                            <td> Edit |
                            <%= link_to '', category, method: :delete, data: { confirm: 'Are you sure?' }, class: 'glyphicon glyphicon-remove' %> </td>
                        </tr>
                        <% end %>
                    </tbody>
                </table>

            </div>

            <div class="col-xs-4">
                <%= render '/categories/form', :locals => {:category => @category} %>
            </div>

        </div>
</div>
<!--/ Full expand -->

This is the form at app/categories/_form.html.erb

<%= simple_form_for(@category, remote: true ) do |form| %>
<%= form.error_notification %>

<div class="form-inputs">
    <%= form.input :content %>
</div>

<div class="form-actions">
    <%= form.button :submit, class: 'btn btn-success custom-reload' %>
</div>

<% end %>

Seems like trouble comes here: at app/controllers/categories_controller.rb

class CategoriesController < ApplicationController
def index
    @user = current_user
    @categories = @user.categories
    @category = Category.new 
  end

  def create
    @user = current_user
    @category = @user.categories.build(category_params)

    respond_to do |format|
      if @category.save
        format.html { redirect_to @categories, notice: 'Category has been sucesifully created' }
        format.js {  }
        format.json { render json: @category, status: :created, location: @category }
      else
        format.js { render @categories, notice: 'Category could not been saved.' }
        format.json { render json: @category.errors, status: :unprocessable_entity }
      end  
    end

  end

  def destroy
    @category = Category.find(params[:id])
    @category.destroy
    redirect_to :back
  end

  private

  def category_params
    params.require(:category).permit(:content)
  end
end

This is app/views/categories/create.html.erb. First line works, second does not.

$("<%= escape_javascript(render @category") %>).appendTo("#categories")
$('.custom-reload').on('click', function() {    
    window.location.reaload();
});

Please, help, does someone knows how to refresh the page. Even, better, does someone have a full example of this kind of common usage of forms inside listings? (I am still not even trying to edit, but delete works already). Thanks.

Change scope to use sql

I have two ruby scope but they are not completely using activecord. How can I change it to use only activerecord or sql?

article.rb

class Article < Comfy::Cms::Page
  has_many :view_mappings
  has_many :favorite_mappings
  scope :top_by_number_of_favorites, -> { article.sort_by(&:favorite_score).take(10) }

  scope :top_by_number_of_views, -> { article.sort_by(&:view_score).take(10) }

  def favorite_score
    favorite_mappings.since(2.weeks.ago).count * 5
  end

  def view_score
    view_mappings.since(2.weeks.ago).count
  end

schema.rb

  create_table "view_mappings", force: :cascade do |t|
    t.integer  "article_id"
    t.date     "date_viewed"
    t.string   "device_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  create_table "favorite_mappings", force: :cascade do |t|
    t.integer  "article_id"
    t.string   "device_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.date     "date_liked"
  end

Rails instance variables display in development but not on Heroku

I am creating an app with Rails 4.2.3 and Postgres database in development and production, deploying to Heroku. Both my dev and production environment are seeded with the same data.

I have three tables - Cities, Neighborhoods, Venues.

class Venues < ActiveRecord::Base
  belongs_to :neighborhood
end
class Neighborhood < ActiveRecord::Base
  belongs_to :city
  has_many :venues
end
class City < ActiveRecord::Base
  has_many :neighborhoods
end

On the app/views/neighborhoods/show.html.erb page I want to display the Venues that belong to that neighborhood.

The app/controllers/neighborhoods_controller.rb show action is this:

def show
  @city = City.find(params[:city_id])
  @neighborhood = @city.neighborhoods.find(params[:id])
  @venues = Venue.where(neighborhood_id: @neighborhood)
end

The neighborhood routes are embedded in the cities routes, but venues are a separate resource not embedded.

resources :cities do
  resources :neighborhoods
end
resources :venues

The Neighborhood show page for any particular neighborhood displays the neighborhood name, city name, then checks if there are any venues via the @venues instance variable. If so it iterates over each of them, otherwise it states there are no venues. app/views/neighborhoods/show.html.erb

<h1><%= @neighborhood.hood_name + ', ' + @city.city_name %></h1>
<% if @venues.present? %>
  <h3>Venues</h3>
  <% @venues.each do |venue|  %>
    <p><%= link_to venue.venue_name, venue %></p>
  <% end %>        
<% else %>
  <p>There are no venues in this neighborhood</p>
<% end %>

This works fine on my mac in dev mode, but when I load it to Heroku the @venues instance variable is always nil. I confirmed using irb and the console that the venues are indeed in the database on Heroku. They just aren't being recognized. Any idea how to fix this? The logs don't give any clues. From a gem perspective, beside the pg gem, in production I am using gem 'rails_12factor', '0.0.3' and 'puma','~> 2.12.2'.

Additional Information

I tried to just pass a simple instance variable from the controller to the show page for both the cities controller/show page and neighborhood controller/show page. app/controllers/cities_controller.rb

    def show
      @hellocity = "Hello from the show action in the cities controller."
    end

app/controllers/neighborhoods_controller.rb

    def show
      @hellohood = "Hello from the show action in the neighborhoods controller."
    end

Then in the views I called each: app/views/cities/show.html.erb

<%= @hellocity %>

app/views/neighborhoods/show.html.erb

<%= @hellohood %>

The result is in my development environment when I go to any city page I get the hellocity message and when I go to any neighborhood page I get the hellohood message. But when I put this on Heroku I only get the message on the city page. The instance variable is not getting passed to the app/views/neighborhoods/show.html.erb page. @neighborhoods and @cities are being passed but anything else (e.g., @hellohood or @venues) is being blocked. Very strange.

Frontend vs Backend validations | Ruby on Rails

When is a better to use js/frontend and ActiveRecord/backend validatons?

After watching various RailsCasts I came up with a thought that I should reduce backend requests as much as possible. Is that right?

Thanks!

HTTParty is escaping JSON

I'm using HTTParty to send data to a remote API, however the API is complaining because the JSON being sent by HTTParty appears to be being escaped, and is thus deemed invalid.

Here's what I'm doing:

query = {"count"=>1,
 "workspaces"=>
  {123445=>
    {"title"=>"Test Project",
     "description"=>"",
     "start_date"=>"2015-06-01T00:00:00.000Z",
     "due_date"=>"2015-08-31T00:00:00.000Z",
     "price_in_cents"=>8000,
     "currency"=>"USD",
     "status_key"=>130,
     "custom_field_values_attributes"=>[],
     "workspace_groups_attributes"=>
      [{"created_at"=>"2015-07-13T11:06:36-07:00",
        "updated_at"=>"2015-07-13T11:06:36-07:00",
        "name"=>"Test Customer",
        "company"=>true,
        "contact_name"=>nil,
        "email"=>nil,
        "phone_number"=>nil,
        "address"=>nil,
        "website"=>nil,
        "notes"=>nil,
        "id"=>"530947",
        "custom_field_values_attributes"=>[]}],
     "id"=>123445}},
 "results"=>[{"key"=>"workspaces", "id"=>123445}]}

Calling to_json on query escapes the JSON too:

"{\"count\":1,\"workspaces\":{\"123445\":{\"title\":\"Test Project\",\"description\":\"\",\"start_date\":\"2015-06-01T00:00:00.000Z\",\"due_date\":\"2015-08-31T00:00:00.000Z\",\"price_in_cents\":8000,\"currency\":\"USD\",\"status_key\":130,\"custom_field_values_attributes\":[],\"workspace_groups_attributes\":[{\"created_at\":\"2015-07-13T11:06:36-07:00\",\"updated_at\":\"2015-07-13T11:06:36-07:00\",\"name\":\"Test Customer\",\"company\":true,\"contact_name\":null,\"email\":null,\"phone_number\":null,\"address\":null,\"website\":null,\"notes\":null,\"id\":\"530947\",\"custom_field_values_attributes\":[]}],\"id\":123445}},\"results\":[{\"key\":\"workspaces\",\"id\":123445}]}"

Is this expected behavior to escape the JSON? Or I'm wondering if the hash I'm building for query is invalid for JSON purposes?

Any help would be greatly appreciated.

Font is displayed differently after migrating to HAML in Rails 4 app

I just migrated my rails app to HAML and since then, my fonts are displayed differently. See the images below for a comparison.

Before: http:///i.imgur.com/x3CjOhE.jpg

After: http://ift.tt/1MzpYmK

I migrated using rake haml:erb2haml included with haml-rails.

If I check out my master branch, it returns to normal. The stylesheets haven't changed and I've confirmed they're loading as normal.

application.html.haml

!!!
%html
  %head
    %meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
    %title= full_title(yield(:title))
    = stylesheet_link_tag 'application', media: 'all', |
      'data-turbolinks-track' => true                  |
    = javascript_include_tag 'application', 'data-turbolinks-track' => true
    = csrf_meta_tags
    = render 'layouts/shim'
  %body
    = render 'layouts/header'
    .container
      - flash.each do |message_type, message|
        %div{:class => "alert alert-#{message_type}"}= message
      = yield
    = render 'layouts/footer'
    = debug(params) if Rails.env.development?

application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title><%= full_title(yield(:title)) %></title>
    <%= stylesheet_link_tag 'application', media: 'all',
                                           'data-turbolinks-track' => true %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
    <%= csrf_meta_tags %>
    <%= render 'layouts/shim' %>
  </head>
  <body>
    <%= render 'layouts/header' %>
      <div class="container">
        <% flash.each do |message_type, message| %>
          <div class="alert alert-<%= message_type %>"><%= message %></div>
        <% end %>
        <%= yield %>
      </div>
    <%= render 'layouts/footer' %>
    <%= debug(params) if Rails.env.development? %>
  </body>
</html>

Can anybody shed some light on why this might be happening?

Cannot save with AngularJS to Rails Backend

We are creating a "twitter clone" using Angular JS and Rails postgresql backend. We have a form to submit new content for a tweet. We have been using AngularJS Resource to grab jSON objects. This is the form below:

<section id="tweet-box" ng-controller="TweetController" action="/tweets" method="post">
    <p id="tweet-box-title">Compose New Tweet</p>
    <form id="tweet-form" ng-submit="addTweet()">
      <textarea id="new-tweet" cols="30" rows="5" maxlength="140" name="tweet" ng-model="content"></textarea>
      <button type="submit" value="Tweet">Add Tweet</button>
    </form>
</section> 

Here is our AngularJS Code. tweetApp is our entire App; the factory grabs our 50 most recent Tweets as jSON. The addTweet() function is what we're trying to have save our data to our database.

var tweetApp = angular.module("tweetApp", ['ngResource']);

tweetApp.factory("RecentTweets", function($resource)
{
  return $resource("/tweets/recent");
});

tweetApp.controller("TweetController", function($scope, RecentTweets)
{
  $scope.tweets = RecentTweets.query(function(data)
  {
    data;

  });
  $scope.addTweet = function(){
    if ($scope.content){
    $scope.tweet = new Tweet();
    $scope.tweet.content = $scope.content;

    // Tweet.save($scope.tweet);
    $scope.tweet.$save(function(msg, header){
    });
    }
    $scope.content = null;
  }
});

At the very end, $save vs .save both come up as not a function in our console. We have tried Tweet.save as well as $scope.content.$save as well as other iterations. Please advise. Thanks!

Rails validate only one enter per pair of db_columns

How can I validate that there can only be one enter with the same doctor_id and patient_id? (a patient can only recommend a doctor once)

class DoctorRecommendation < ActiveRecord::Base
  belongs_to :patient, :class_name => "User"
  belongs_to :doctor, :class_name => "User"

  validates :patient, presence: true
  validates :doctor, presence: true
  # does not work
  validates_uniqueness_of :recommend, scope: [:doctor_id, :patient_id]

end

Rails google oauth2 google drive API with my own account

I'm having some difficulty understanding how to use the google api with my rails app. I've already setup devise and oauth2 where I can authenticate and create google users.

The problem is that I want to create folders, documents, and spreadsheets on my own account.

So I want my user to click "create document" and I want to create a document, save it to my own Gdrive and share the edit link.

Is there a way to get a permanent oauth2 token for myself and then use it? How would you go about setting that up.

I will have to make sure the scope is setup for drive and docs when authenticating but that's as far as I got while reading up here:

http://ift.tt/1Df1IVn and I'm using this for oauth2 with devise so already have client info: http://ift.tt/1bPF9J2

I think I have most of the infrastructure but need that extra push to get my own permanent tokens and figure out how to make my own model that will interact with google.

Any help appreciated.

How to enable pagespeedy admin pages?

after ty hard i got it, install the nginx (from source) with passenger and google pagespeed. I've setup the nginx conf and it worked but, i dint see any diference using pagespeedy(my scripts stills unminified). Studyng a little i saw that PGSPD have an admin page where i can see what is happening and configure somethings. So i can't access this admin pages here is my nginx conf:

#user  nobody;
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    passenger_root /home/icaro/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/passenger-5.0.15;
    passenger_ruby /home/icaro/.rbenv/shims/ruby;
    sendfile        on;
    #tcp_nopush     on;
    #keepalive_timeout  0;
    keepalive_timeout  65;
    gzip  on;
    server {
        listen 80;
        pagespeed on;
        pagespeed FileCachePath /tmp/pgsp;
        passenger_enabled on;
        passenger_app_env production;
        root /home/icaro/icarodroplet/public;
    }
    server{
        pagespeed on;
        pagespeed FileCachePath /tmp/pgsp;
        location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" {
          add_header "" "";
        }
        location ~ "^/pagespeed_static/" { }
        location ~ "^/ngx_pagespeed_beacon$" { }
        location /ngx_pagespeed_statistics { allow 127.0.0.1; allow all; }
        location /ngx_pagespeed_global_statistics { allow 127.0.0.1; allow all; }
        location /ngx_pagespeed_message { allow 127.0.0.1; allow all; }
        location /pagespeed_console { allow 127.0.0.1; allow all; }
        location ~ ^/pagespeed_admin { allow 127.0.0.1; allow all; }
        location ~ ^/pagespeed_global_admin { allow 127.0.0.1; allow all; }
    }
}

that's right? why i cant see differences there is a way to test the pagespeed? how can i access the admin pages?

RSpec - Error when testing nested index route

I have my photo actions nested under restaurant actions as so:

resources :restaurants do
    resources :photos
end

However when I run my test:

describe PhotosController do
  it { should route(:get, "/restaurants/:restaurant_id/photos").to(action: :index) }
end

I get the error:

1) PhotosController should route GET /restaurants/:restaurant_id/photos to/from {:action=>"index", :controller=>"photos"}
     Failure/Error: it { should route(:get, "/restaurants/:restaurant_id/photos").to(action: :index) }
       The recognized options <{"controller"=>"photos", "action"=>"index", "restaurant_id"=>":restaurant_id"}> did not match <{"action"=>"index", "controller"=>"photos"}>, difference:.
       --- expected
       +++ actual
       @@ -1 +1 @@
       -{"action"=>"index", "controller"=>"photos"}
       +{"controller"=>"photos", "action"=>"index", "restaurant_id"=>":restaurant_id"}
     # ./spec/controllers/photos_controller_spec.rb:4:in `block (2 levels) in <top (required)>'

I checked my route paths via rake routes and got the following:

restaurant_photos  GET /restaurants/:restaurant_id/photos(.:format)  photos#index

What am I doing wrong?

Rails Omniauth missing required parameter: code

Running rails 3.2.18 on c9.io, and I have the gems omniauth and omniauth-google-oauth2 installed. I ran into a problem where I would get a CSRF error on the callback, and it sounded like adding "provider_ignores_state: true" to the params would prevent that, at least for testing and development. It did get rid of the CSRF error, but now there is a new error:

OAuth2::Error

invalid_request: Missing required parameter: code
{
  "error" : "invalid_request",
  "error_description" : "Missing required parameter: code"
}

my config/initializers/omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
    provider :google_oauth2, "clientID", "clientSecret",
    scope: 'profile', image_aspect_ratio: 'square', image_size: 48, access_type: 'online', name: 'google', provider_ignores_state: true
end

Top few lines from the trace:

oauth2 (1.0.0) lib/oauth2/client.rb:113:in `request'
oauth2 (1.0.0) lib/oauth2/client.rb:138:in `get_token'
oauth2 (1.0.0) lib/oauth2/strategy/auth_code.rb:29:in `get_token'
omniauth-oauth2 (1.3.1) lib/omniauth/strategies/oauth2.rb:93:in `build_access_token'
omniauth-google-oauth2 (0.2.6) lib/omniauth/strategies/google_oauth2.rb:77:in `custom_build_access_token'

EDIT: Adding the versions for the gems

/usr/local/rvm/gems/ruby-1.9.3-p547/gems/omniauth-1.2.2
/usr/local/rvm/gems/ruby-1.9.3-p547/gems/omniauth-google-oauth2-0.2.6

Setitng custom field values doesn't work with Paranoia

I have been trying to set up Paranoia with my project. I have a deleted_at column and another column status which is equal to 2 when it's deleted.

Model Class

class Account < ActiveRecord::Base

  acts_as_paranoid column: :status, sentinel_value: 1

  def paranoia_restore_attributes
    {
      deleted_at: nil,
      status: 1
    }
  end

  def paranoia_destroy_attributes
    {
      deleted_at: current_time_from_proper_timezone,
      status: 2
    }
  end 
end

But when I perform destroy or restore, it doesn't seem to change the status value.

Masonry JQuery with Rails for Transistions - Need to refresh page for it to work

I am using masonry rails gem in order to have my posts nicely transition depending on the screen size and stuff but for some reason I always need to refresh the page in order for masonry to start working. Whenever I first visit a page it has all the posts in one column on the left hand side of the screen, then when I refresh the page is displays the posts properly using the masonry transitions. Has any one experienced this before or possible know a solution to resolve this?

Thanks in advanced!

UPDATE: looking into the console as I thought maybe some css ids or classes weren't being applied on the first load but they all are. I also had disable cache checked so I thought that could have been causing it but after unchecking it the problem persists.

I would greatly appreciate any input on what may be causing this.