lundi 29 février 2016

Errors is deploying rails application on Opsworks AWS.

this is file log file please have a look. IF says something we are sorry went wrong, If you are the application owner check the logs for more information.

http://ift.tt/1QiLldc

Ec2 rails console accentuation

I tryng to put on db some words that have accentuation like São Paulo. i'm using postgres with Latin1 Encoding and this should solve the problem. but did not solve. So someone had this issue? this is a postgres problem?

thank's

jquery autocomplete Cannot read property 'replace' of undefined

$('#tags').autocomplete({
    params: {search_type:$('#search-type').val()},
    minChars: 2,
    appendTo: $(".cash-collection-select"),
    serviceUrl: '/admin/journals/search_roles',
    onSelect: function (suggestion) {
      $("#q").val(suggestion.data);
      console.log(suggestion.data)
      alert("You selected: ' + suggestion.value + ', ' + suggestion.data")
    },
    onSearchStart: function(query) {
    console.log("query: "+query)
    },
    onSearchComplete: function (query, suggestions) {
      console.log(suggestions.data)
    }
  });

I am getting the error Cannot read property 'replace' of undefined. My response from the rails action is coming in json format

suggestions = User.where("email LIKE ?","#{params[:query]}%")
    message = {:query => "Unit", :suggestions => suggestions}
    render :json => message

this is my input #tags

<input class="search-emails" type="email" id="tags" placeholder="Search by email.." />

Unable to control memory utilization on server increasing with ruby process

I have a Rails 3.2 application running on production server. The server has 8 GB of RAM and every other process works fine. But, there is a ruby process which keeps the memory utilization on the higher side. I have to manually login to the server console and type the TOP command and kill the process using the PID.

But, I am unable to figure out how to check which ruby process is taking so much of memory and also how to control it permanently.

Please suggest me a solution.

Thanks.

Rails 3 Ajax-JQuery: view not updated when destroying an object

I encounter an issue when I destroy an object in AJAX with Rails 3.2.11.

I followed this tutorial: http://ift.tt/1DGQ2KV

The controller works fine, but in the view, nothing is done properly. I think my problem is JQuery, but I'm not sure, so where is my problem?

//views/tournaments/index.html.haml
%table.table.table-hover.table-bordered
 %thead
  %th Name
  %th Place
  %th Nb players max
  %th
  - if can? :update, @tournaments
   %th
  - if can? :destroy, @tournaments
   %th
 - @tournaments.each do |tournament|
  %tr
   %td= tournament.name
   %td= tournament.place
   %td= tournament.nb_players_max
   %td= link_to 'Show', tournament
   - if can? :update, @tournaments
    %td= link_to 'Edit', edit_tournament_path(tournament)
   - if can? :destroy, @tournaments
    %td= link_to 'Destroy', tournament, method: :delete, data: {confirm: 'Are you sure?'}, :class => 'destroy_tournament', :remote => true

My controller tournaments_controller.rb:

 def destroy
  @tournament = Tournament.find(params[:id])
  @tournament.destroy

  respond_to do |format|
   format.html { redirect_to tournaments_url }
   format.json { head :no_content }
   format.js   { render :layout => false }
  end
 end

destroy.js.erb:

$('.destroy_tournament').bind('ajax:success', function(){
 $(this).parent('tr').fadeOut(400, function(){
  $(this).remove();
 });
});

The console tells me that the controller works fine (200 OK), and in response, I have the content of the JS file.

What happened? :-(

dimanche 28 février 2016

How to update a column of type text for all customers based on a condition in Rails 4

I have a customer model and controller in my rails application. In my customers listing index page I am displaying all customers with search filter options to display customers according to their purchase type (Sale, Lease, Trial).

@customers = Customer.where(customer_type: ["Sale","Lease","Trail"]).count

If the count > 0 I want to update their customer_type field to its capitalized form (Sale -> SALE , Lease -> LEASE, Trail -> TRAIL) for all customers in the @customers collection .

How to achieve it in a most optimised way ?

Ruby on Rails: how can I show a variable and then exit?

I am still working on my small app interacting with the Steam API. I am fiddling with Nokogiri and regexps among other things and I want to output a certain variable before stopping the script. This is in a viewless action where, at the end of the process the user will be redirected to another action with a view.

I tried puts then exit but Apache hangs and I have to restart it manually. Since most of the time I want to display the variable from inside a loop, I don't want to let the rest of the script continue. Is there a way I can just show the variable's contents and the terminate the script execution from the controller? If it's not possible I could deal with logging the variable's contents before terminating the script instead of outputting it.

Ruby on Rails Students Marks & Grades App

I'm very new to RoR.. So Please forgive me if you feel this question very basic I'm creating an app which takes students marks as input and Grade as output. I've Students_controller.rb , student.rb .

I need to put logic like this:

def grade(m) if m>80 g="A" else g="B" end

I would be really happy if you let me know where I should place this code

samedi 27 février 2016

Rails Missing helper file application_helper.rb_helper.rb

OS: Windows 10 x64 Rails: 4.2.5.1 Ruby: 2.2.4

Hello, I am running rails on windows and installed it with the Rails Installer. On a fresh generated application I get this error:

Missing helper file helpers/c:/myapp/app/helpers/application_helper.rb_helper.rb

When I create the file named application_helper.rb_helper.rb. The error changes to:

uninitialized constant C

I am creating my own thread for this because every other user who had this issue seems to in a folder called user; mine is not. I assume this is because I am on windows and do not have RVM.

NameError in Users#show - Rails

I am following Michael Hurtl's Rails Tutorial and In Chapter 11 When i want to view the profile page of the User i get this error :

NameError in Users#show undefined local variable or method `micropost' and This line of Code is highlighted in red :

<%= link_to micropost.user.name , micropost.user%>

Here's My code:

microposts_controller.rb

class MicropostsController < ApplicationController
        before_action :authenticate_user! , only: [:create,:destroy]

    def create
        @micropost = current_user.microposts.build(micropost_params)

        if @micropost.save
            flash[:success] = "Micropost created"
            redirect_to root_url
        else
            render 'pages/home'
        end
    end

    def destroy
    end

    private

    def micropost_params
        params.require(:micropost).permit(:content)
    end
end

users_controller.rb

class UsersController < ApplicationController
    before_action :authenticate_user! , only: [:edit,:update,:destroy]

    def index
        @users = User.all
    end

    def show
        @user = User.find(params[:id])
        @microposts = @user.microposts
    end

end

microposts/_microposts.html.erb

<%= link_to micropost.user.name , micropost.user%>

nil can't be coerced into Float,help please

I am having one problem. Hope someone can help..I have this error

"Action controller Error is : /app/views/carts/show.html.erb where line #6 raised:

" nil can't be coerced into Float "

Here are the code file

Cart Item Model

class CartItem


attr_reader :product_id, :quantity



def  initialize (product_id, quantity= 1)
    @product_id = product_id
    @quantity = quantity
  end

  def increment
     @quantity = @quantity + 1
  end

  def product
    Product.find product_id
  end

  def total_price
    product.price * quantity
  end
end

Show View

<% @cart.items.each do |item|%>
<table class="table table-hover">
  <tr>
    <td><%= item.quantity %></td>
    <td><%= item.product.name %></td>
    <td><%= item.total_price %></td>
  </tr>
</table>

<% end %>

Cart Controller

class CartsController < ApplicationController
  before_filter :initialize_cart

  def add
    @cart.add_item params[:id]
    session["cart"] = @cart.serialize
    product = Product.find params[:id]
    redirect_to :back, notice:  "Added #{product.name} to cart."
  end

  def show

  end

end

Thank you in advance

chef bash scope issues with commands.

I have a chef recipe that goes to github and clones a repo. Unfortunately, I dont have git configured to use the certs and hence it has issues using https protocol with github.com.

My temp solution is to run the following and dont check for ssl.

git config --global http.sslVerify false

This works when I do it manually so I put it in a bash block :

bash 'SSLVerify=False' do
  user 'root'
  cwd '/home'
  code <<-EOH
    git config --global http.sslVerify false
    echo "SSL Check Disabled for git"
    EOH
end

This succeeds and gives me the echo, but as the chef recipe comes to github clone part it fails again. Is the scope or bash only for the code in it or globally ?

undefined method `article_name' .................NoMethodError in ArticlesController#create

class ArticlesController < ApplicationController def index @articles = Article.all end def show @article = Article.find(params[ :id]) end def new @article = Article.new end def create @article = Article.new(article_params) if @article.save redirect_to @article else render 'new' end end

private
 def article_params
       params.require(:article).permit(:Article_name,:enter_text)
end

end

How can I update rails older version to new version

In my system I have rails 4.2.5 and ruby 2.2.3.

how can I update to rails 5.0.0.beta version.

Thank you.

vendredi 26 février 2016

Rails simple model attributes not saved to database

I am developing a small Rails 3 app that reads data from the Steam API. What I am seeing is that the model attributes for any ActiveRecord model I create are not saved to the database nor are they output if I debug them.

Here my sample model

class NonPlayableApp < ActiveRecord::Base
  attr_accessor :name, :steam_id
  attr_accessible :name, :steam_id
end

With the migration file being:

class CreateNonPlayableApps < ActiveRecord::Migration
  def change
    create_table :non_playable_apps do |t|
      t.string :name
      t.string :steam_id
      t.timestamps
    end
  end
end

Here are few tests with the Rails console, I get the same results when I try them in a controller and inspect or yaml the model:

irb(main):001:0> temp = NonPlayableApp.new( steam_id: 33333, name: "Testing" )
=> #<NonPlayableApp id: nil, name: nil, steam_id: nil, created_at: nil, updated_at: nil>
irb(main):002:0> temp.steam_id
=> 33333
irb(main):003:0> temp.name
=> "Testing"
irb(main):004:0> temp.save
   (0.1ms)  begin transaction
  SQL (4.0ms)  INSERT INTO "non_playable_apps" ("created_at", "name", "steam_id", "updated_at") VALUES (?, ?, ?, ?)  [["created_at", Fri, 26 Feb 2016 19:40:37 UTC +00:00], ["name", nil], ["steam_id", nil], ["updated_at", Fri, 26 Feb 2016 19:40:37 UTC +00:00]]
   (8.8ms)  commit transaction
=> true
irb(main):005:0> temp.steam_id
=> 33333
irb(main):006:0> temp
=> #<NonPlayableApp id: 64, name: nil, steam_id: nil, created_at: "2016-02-26 19:40:37", updated_at: "2016-02-26 19:40:37">
irb(main):007:0> temp2 = NonPlayableApp.first
  NonPlayableApp Load (1.6ms)  SELECT "non_playable_apps".* FROM "non_playable_apps" LIMIT 1
=> #<NonPlayableApp id: 64, name: nil, steam_id: nil, created_at: "2016-02-26 19:40:37", updated_at: "2016-02-26 19:40:37">
irb(main):008:0> temp2.steam_id
=> nil
irb(main):009:0> temp2.name
=> nil

What am I missing?

Updating Rails version of an application

I currently work in a big Rails App that sadly has no test coverage and is currently on version 3 of Rails.

What would be the best approach in order to migrate to Rails 4 ? I know it's better to migrate step by step on Rails version, but the application is very big.

Should I invest in Tests before doing so ? What kind of tests ? Unit testing ? Integration tests ?

Rails devise omniauth facebook

I can't get devise omniauth-facebook to work. I've followed the devise guide to no avail. I think my problem is the model is not retrieving info.

Model

class User < ActiveRecord::Base
  has_attached_file :image, styles: {large: "1920x1080#", medium:              "800x500#", thumb: "100x100"}, :default_url =>    "/images/:style/missing.png"
  validates_attachment_content_type :image, :content_type =>    ["image/jpg", "image/jpeg", "image/png", "image/gif"]

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable,
     :omniauthable, :omniauth_providers => [:facebook]
  def admin?
    admin
  end

  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]
      user.name = auth.info.name   # assuming the user model has a     name
      user.image = auth.info.image # assuming the user model has an image
      puts request.env["omniauth.auth"]
    end
  end

  def self.new_with_session(params, session)
    super.tap do |user|
      if data = session["devise.facebook_data"] &&     session["devise.facebook_data"]["extra"]["raw_info"]
        user.email = data["email"] if user.email.blank?
      end
    end
  end
end

Routes.rb

Rails.application.routes.draw do

  mount RailsAdmin::Engine => '/admin', as: 'rails_admin'

  devise_for :users do
    delete 'logout' => 'sessions#destroy', :as => :destroy_user_session,
    :controllers => { :omniauth_callbacks => "user/omniauth_callbacks" }
  end

Controller

class User::OmniauthCallbacksController <         Devise::OmniauthCallbacksController
  # You should configure your model like this:
  # devise :omniauthable, omniauth_providers: [:twitter]

  # You should also create an action method in this controller like this:
  # def twitter
  # end
  def facebook
    # You need to implement the method below in your model (e.g. app/models/user.rb)
    @user = User.from_omniauth(request.env["omniauth.auth"])
    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

  def self.new_with_session(params, session)
    if session["devise.user_attributes"]
      new(session[devise.user_attributes], without_protection: true) do |user|
        user.attributes = params
        user.valid?
      end
    else
      super
    end

After I click "Login with facebook", it directs to a facebook url, I input a password, press enter, get redirected to the same page with a long url. (http://localhost:3000/demographics?code=AQDK1z40APoLiWykomxDDUljBUNHotenM4lzj_bZMhH8iQ74J_Nu_EUnPqBqkbNAeWQEPZwQs7YghqkB4eD7AoQLkN_RuYIlmotMtrJc4UyGRSe3CJIHcxp6kcB9BuYHA_Ldz0NMJvvGzOuvC-uDpFn6TyrzvV5v9LvivORXVduSsCy7_r6PcW8jxAkWqZzKyASXf26h8h3f_kha2d0KX6Ygft8ozN1HT9Xr-1y7ZtIKgTXEGMrqK950kASv2oTE0tQ5CYt6mfEZsVyLpykYIApOls8NLhjOaOIJewzV9EnLdSq0FbrvtedhhDmy-hg6IkRAbRVgwEkfUFsi9DXoxKyX&state=bdbf498f33f67ef57f3f54b846f870f21bb80c039c099f1a#=)

The best Audio Upload with a Rails CRUD

I try to create audio player in a specific rails New simpleform.

Just a brief message I want to publish flip flashcard (Actually I generate Hiragana) with a audio button to listen to the word with an audio player.

I am asking what is the best solution to upload audio files? Actually I try to do that with the Cloudinary video storage service.

I create a sound uploader with CarrierWave gem like this :

# encoding: utf-8

class SoundUploader < CarrierWave::Uploader::Base
  include Cloudinary::CarrierWave

  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  # include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url
  #   # For Rails 3.1+ asset pipeline compatibility:
  #   # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
  #
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end

  # Process files as they are uploaded:
  # process :scale => [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  # version :thumb do
  #   process :resize_to_fit => [50, 50]
  # end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  # def extension_white_list
  #   %w(jpg jpeg gif png)
  # end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  # def filename
  #   "something.jpg" if original_filename
  # end

end

Then In my model I call the MountUploader with this code (the object I call is sound) :

class Hiragana < ActiveRecord::Base
  belongs_to :user
  has_many :favs, dependent: :destroy

  mount_uploader :upload, ImageUploader

  mount_uploader :sound, SoundUploader

end

The upload is created in View New : Please check the picture enter image description here

My Question is How do I call the Upload? I mean I put in my code this varial @hiragana.sound but could you have a look on the error picture enter image description here

Thank you for your help.

Testing nested routes in rails

I was writing integrations tests for my application. I am familiar with the controller tests and the normal integration testing. However, I am not sure how to test nested resources in the integration testing. I have a teams model which is nested inside the scoreboards model. The relevant routes code is given below.

resources :scoreboards do 
   resources :teams, only: [:edit, :create, :destroy, :update]
 end

I want to test all the important workflows for teams. For example, the invalid and valid creation of teams. The test code is written below.

def setup
    ActionMailer::Base.deliveries.clear
    @scoreboard = scoreboards(:scoreboard_a)
  end



test 'Invalid creation of the teams' do
    assert_no_difference 'Team.count' do
      post scoreboards_teams_path(@scoreboard), team: {name: " ", 
                                                        win: 0, 
                                                       loss: 0, 
                                                        tie: 0 }

    end
  end 

I have the validation set up in such a way that team name must be present. The problem is with the routes. I also have an association set up with scoreboard_a. The teams.yml file is given below.

team_a:
    name: team
    win: 1
    loss: 2
    tie: 0
    id: 2
    scoreboard: scoreboard_a 

I get a no method error. The error is given below.

`NoMethodError: undefined method `scoreboards_teams_path'. 

Since teams are nested inside scoreboards show page. Therefore, there isn't a new action I can call the get request to. My question is, how would I call a post request to the teams object. I am not exactly sure how to do that. I have tried looking through documentation but there isn' really anything on nested routes. I have other objects that are nested inside scoreboards as well. Therefore, understanding how nested routes are tested in rails would really go a long way. As always, any help is greatly appreciated. Thanks!!

active_support/dependencies.rb:142:in `load_without_new_constant_marking': no such file to load -- mongrel_rails (MissingSourceFile)

from /home/jhipster/.rvm/gems/ruby-1.8.7-head/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in load' from /home/jhipster/.rvm/gems/ruby-1.8.7-head/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:innew_constants_in' from /home/jhipster/.rvm/gems/ruby-1.8.7-head/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in load' from /home/jhipster/.rvm/gems/ruby-1.8.7-head/gems/rails-2.2.2/lib/commands/servers/mongrel.rb:64 from /home/jhipster/.rvm/gems/ruby-1.8.7-head/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:inrequire' from /home/jhipster/.rvm/gems/ruby-1.8.7-head/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in require' from /home/jhipster/.rvm/gems/ruby-1.8.7-head/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:innew_constants_in' from /home/jhipster/.rvm/gems/ruby-1.8.7-head/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in require' from /home/jhipster/.rvm/gems/ruby-1.8.7-head/gems/rails-2.2.2/lib/commands/server.rb:49 from server:3:inrequire' from server:3

undefined method `next_element' for #

I want to get the next element text by previous I'm doing like this

property_doc = Nokogiri::HTML(open(my_url))

address = property_doc.xpath('//section[@class="container"]/dl/dt[contains(text(), "Address")]').next_element.text

but error occurred undefined method 'next_element' for #<Nokogiri::XML::DTD:0x....>

I want to next element text which is showing at html :

<section class="container">
<dl>
<dt>Address</dt>
<dd class="">550 Seagaze Dr<br>Oceanside CA 92054 </dd>
</dl>
</section>

Ruby on Rails No route matches :action=>"show"

Hello i'm newbie in Ruby on Rails i've got following error

No route matches {:action=>"show", :controller=>"collections"} missing required keys: [:id]

I think problem is occuring in routes and here is my code

<% @collections.take(7).each do |c| %>
            <div class="col-md-3">
            <%= link_to c do %>
                <div class="well" style="background: 
                        linear-gradient(
                          rgba(1, 0, 0, 0.4), 
                          rgba(1, 0, 0, 0.4)
                        ),
                        url(<%= c.avatar.url %>);
                        background-size: cover;">
                    <h3 class="text-center"><%= c.name %></h3>
                    <h6 class="text-center">30 places</h6>
                </div>
                <% end %>
            </div>
        <% end %>

And here is routes.rb

resources :collections, only: [:index, :show]
  root 'pages#index'

  namespace :admin do
    resources :places
    resources :collections, only: [:new, :create]
  end

UPDATE!

Here is my collection controller within Admin namespace

class Admin::CollectionsController

    before_action :authenticate_user!
    layout 'dashboard'

    def new
        @collection = Collection.new
    end

    def create
        @collection = Collection.new(coll_params)

        if @collection.save
            redirect_to new_admin_collection_path
        else
            render 'new'
        end
    end

    def show
    end

    def update
        if @collection.update(coll_params)
            redirect_to @collection
        else
            render 'edit'
        end
    end

    def destroy
        @collection.destroy
        redirect_to root_path
    end

    private

    def find_coll
        @collection = Collection.find(params[:id])
    end

    def coll_params
        params.require(:collection).permit(:name, :avatar)
    end
 end

jeudi 25 février 2016

ruby unzip - fails with uninitialized constant ZIP::File

I have the following ruby code :

require 'HTTPClient'
require 'rubygems'
require 'zip'

def self.unzip(data, dest_dir)
  ::Zip::File.open_buffer(data) do |fzip|
    fzip.each do |entry|
     path = File.join(dest_dir, entry.name)
     puts "here"
     FileUtils::mkdir_p(File.dirname(path))
     fzip.extract(entry, path) unless File.exist?(path)
   #fzip.close
    end
  end
end

def self.fetch_from_url(url, dest_dir)
  response = HTTPClient.get(url, follows_redirect: true)
  if response.status == 200
    unzip(response.body, dest_dir)
  else
    raise 'Could not fetch files from 3scale'
  end
end


url = 'link/artifactory/zip-release-local/djin/3Sroxy/1.0.5/configuration.zip'
fetch_from_url(url, "/Users/something/")

When I run this in Mac ruby 2.0.0p481 it works fine and unzips the folder, but when I run the same in centOS 6.6 in ruby 1.8.7 it fails with following :

[root@ip-10-201-90-206 ~]# sudo ruby test/ex.rb 
test/ex.rb:7:in `unzip': uninitialized constant Zip::File (NameError)
    from test/ex.rb:20:in `fetch_from_url'
    from test/ex.rb:28

why ?

how to order by in rails with priority conditional in attributes

example i have a list of users

id           name         role

1            join         member
2            cathy        sale
3            mark         admin
4            orthor       member
5            Sy           admin

i want to order by role asc with priority when role= 'member'

result:

 id           name         role

1            join         member
4            orthor       member
3            mark         admin
5            Sy           admin
2            cathy        sale

how to order by this in rails??

How to track User Activity

which is best gem to track user activity ?. I have used public_activity gem the problem with that gem is that you have to call activity method from other methods which you want to keep track.

I want something like there should be separate config file where i can mention which methods or actions to be tracked

for example config file

def track
 user index
 user edit
end

any help would be appreciated.

When ActionView::MissingTemplate in Rails happens?

When does ActionView::MissingTemplate usually happens in Rails? I have an API which it can't possibly return above error, but when mobile triggered the routes. It happens two time the ActionView::MissingTemplate error.

Here is a sample code in controller on my API:

def search
  @search_text = params[:search_text]
  unless @search_text.blank?
    @my_models = MyModel.find_all_by_age(@search_text)
  else
    @my_models = []
  end

  render 'api/v4/my_models/show', status: 200, formats: :json
end

On my Routes:

namespace :api, defaults: {format: 'json'} do
  namespace :v4 do
    resource :my_models, only: [:search] do
        get :search
      end
  end
end

I am puzzled when does ActionView::MissingTemplate happens? Could someone point me when does this error happens? Is this mobile missed something in the URL to make this error happen? How?

Thanks!

Why does calling `respond_to?("find_by_identifier")` on a relation instantiate all of the items

class Collection < ActiveRecord::Base
  has_many :items
end

class Item < ActiveRecord::Base
  after_initialize :do_stuff

  def do_stuff
    STDERR.puts "Got here"
  end
end

collection = Collection.where(identifier: "foo").first ; nil
  Collection Load (0.6ms)  SELECT `collections`.* FROM `collections` WHERE `collections`.`identifier` = 'foo' LIMIT 1

[22] pry(main)> collection.items.find_by_identifier!("280") ; nil
  Item Load (1.0ms)  SELECT `items`.* FROM `items` WHERE `items`.`collection_id` = 42 AND `items`.`identifier` = 'bar' LIMIT 1
Got here

[23] pry(main)> collection.items.respond_to?("find_by_identifier!") ; nil
  Item Load (9.7ms)  SELECT `items`.* FROM `items` WHERE `items`.`collection_id` = 42
[Hundreds of of "Got here"s]

In ActiveRecord version 3.2.x, why does running find_by_identifier! only cause one item to be instantiated, but calling respond_to?("find_by_identifier!") cause all of the items in the has_many relationship to be instantiated?

Two legged oauth2 using Doorkeeper

Could I customize OAuth2 + Doorkeeper + Devise as two legged? Because I guess doorkeeper is three legged if I'm right. It is can customize, how could I do it?

Mysql2 error for port

I am not able to setup my database on localhost mac. It consistently asking me to set host. I did through

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

But it didn't worked for me . Could anybody suggest me where i am wrong.

Host '10.18.37.76' is not allowed to connect to this MySQL server

frames routing in erb rails

Two questions.

Number 1:

This is how I am creating the frames in .erb files.

<frameset rows="170,*" frameborder="0" border="0" framespacing="0">
  <frame name="topNav" src="top_nav.html">
  </frame>
</frameset>

I have couple more frames inside above frameset. If I run this code, I get "No route matches [GET] "/top_nav.html". Question is: Is it really necessary to create/config routes of all the src locations specified in the frame tag?

Number 2:

In my application, I would need to change links in my app very frequently. If I need to consider the routing, I would need to create routes more frequently. Right? How can I avoid consider the routes? Basically, If I add any link in my app, it should work irrespective of fact that whether I have added the routes or not.

gem 'mysql2', 0.4.3, in migrating database in Ruby on Rails

Today 25 Feb I hav beene updating my gems in Ruby on Rails and now I have some problems that I don't understand.

Have you got any idea? I have mysql2, version 0.4.3, and active record 4.2.3

Here the error: rake aborted! Gem::LoadError: Specified 'mysql2' for database adapter, but the gem is not loaded. Add gem 'mysql2' to your Gemfile (and ensure its version is at the minimum required by ActiveRecord). /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/connection_adapters/connection_specification.rb:177:in rescue in spec' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/connection_adapters/connection_specification.rb:174:inspec' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/connection_handling.rb:50:in establish_connection' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/railtie.rb:120:inblock (2 levels) in ' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:38:in instance_eval' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:38:inexecute_hook' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:45:in block in run_load_hooks' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:44:ineach' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:44:in run_load_hooks' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/base.rb:315:in' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/base.rb:26:in <top (required)>' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment.rb:56:inconnection_class' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/tenant.rb:64:in config' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/tenant.rb:28:inadapter' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/tenant.rb:19:in init' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/railtie.rb:31:inblock in ' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:444:in instance_exec' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:444:inblock in make_lambda' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:190:in call' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:190:inblock in simple' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:in call' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:inblock in call' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:in each' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:incall' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:88:in run_callbacks' /var/lib/gems/2.1.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/reloader.rb:83:inprepare!' /var/lib/gems/2.1.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/reloader.rb:55:in prepare!' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application/finisher.rb:50:inblock in ' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:30:in instance_exec' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:30:inrun' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:55:in block in run_initializers' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:54:inrun_initializers' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:352:in initialize!' /home/luca/cmonrails/cmonrails/config/environment.rb:5:in' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:328:in require' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:328:inrequire_environment!' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:457:in block in run_tasks_blocks' Gem::LoadError: can't activate mysql2 (~> 0.3.13), already activated mysql2-0.4.2. Make sure all dependencies are added to Gemfile. /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/connection_adapters/mysql2_adapter.rb:3:in' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:274:in require' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:274:inblock in require' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:240:in load_dependency' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:274:inrequire' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/connection_adapters/connection_specification.rb:175:in spec' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/connection_handling.rb:50:inestablish_connection' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/railtie.rb:120:in block (2 levels) in <class:Railtie>' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:38:ininstance_eval' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:38:in execute_hook' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:45:inblock in run_load_hooks' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:44:in each' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:44:inrun_load_hooks' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/base.rb:315:in <module:ActiveRecord>' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/base.rb:26:in' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment.rb:56:in connection_class' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/tenant.rb:64:inconfig' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/tenant.rb:28:in adapter' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/tenant.rb:19:ininit' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/railtie.rb:31:in block in <class:Railtie>' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:444:ininstance_exec' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:444:in block in make_lambda' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:190:incall' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:190:in block in simple' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:incall' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:in block in call' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:ineach' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:in call' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:88:inrun_callbacks' /var/lib/gems/2.1.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/reloader.rb:83:in prepare!' /var/lib/gems/2.1.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/reloader.rb:55:inprepare!' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application/finisher.rb:50:in block in <module:Finisher>' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:30:ininstance_exec' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:30:in run' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:55:inblock in run_initializers' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:54:in run_initializers' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:352:ininitialize!' /home/luca/cmonrails/cmonrails/config/environment.rb:5:in <top (required)>' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:328:inrequire' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:328:in require_environment!' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:457:inblock in run_tasks_blocks' Tasks: TOP => db:migrate => environment (See full trace by running task with --trace) luca@luca-X200MA:~/cmonrails/cmonrails$ rake db:migrate rake aborted! Gem::LoadError: Specified 'mysql2' for database adapter, but the gem is not loaded. Add gem 'mysql2' to your Gemfile (and ensure its version is at the minimum required by ActiveRecord). /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/connection_adapters/connection_specification.rb:177:in rescue in spec' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/connection_adapters/connection_specification.rb:174:inspec' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/connection_handling.rb:50:in establish_connection' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/railtie.rb:120:inblock (2 levels) in ' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:38:in instance_eval' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:38:inexecute_hook' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:45:in block in run_load_hooks' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:44:ineach' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:44:in run_load_hooks' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/base.rb:315:in' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/base.rb:26:in <top (required)>' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment.rb:56:inconnection_class' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/tenant.rb:64:in config' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/tenant.rb:28:inadapter' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/tenant.rb:19:in init' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/railtie.rb:31:inblock in ' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:444:in instance_exec' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:444:inblock in make_lambda' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:190:in call' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:190:inblock in simple' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:in call' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:inblock in call' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:in each' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:incall' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:88:in run_callbacks' /var/lib/gems/2.1.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/reloader.rb:83:inprepare!' /var/lib/gems/2.1.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/reloader.rb:55:in prepare!' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application/finisher.rb:50:inblock in ' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:30:in instance_exec' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:30:inrun' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:55:in block in run_initializers' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:54:inrun_initializers' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:352:in initialize!' /home/luca/cmonrails/cmonrails/config/environment.rb:5:in' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:328:in require' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:328:inrequire_environment!' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:457:in block in run_tasks_blocks' Gem::LoadError: can't activate mysql2 (~> 0.3.13), already activated mysql2-0.4.2. Make sure all dependencies are added to Gemfile. /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/connection_adapters/mysql2_adapter.rb:3:in' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:274:in require' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:274:inblock in require' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:240:in load_dependency' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:274:inrequire' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/connection_adapters/connection_specification.rb:175:in spec' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/connection_handling.rb:50:inestablish_connection' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/railtie.rb:120:in block (2 levels) in <class:Railtie>' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:38:ininstance_eval' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:38:in execute_hook' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:45:inblock in run_load_hooks' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:44:in each' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:44:inrun_load_hooks' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/base.rb:315:in <module:ActiveRecord>' /var/lib/gems/2.1.0/gems/activerecord-4.2.3/lib/active_record/base.rb:26:in' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment.rb:56:in connection_class' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/tenant.rb:64:inconfig' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/tenant.rb:28:in adapter' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/tenant.rb:19:ininit' /var/lib/gems/2.1.0/gems/apartment-1.0.2/lib/apartment/railtie.rb:31:in block in <class:Railtie>' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:444:ininstance_exec' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:444:in block in make_lambda' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:190:incall' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:190:in block in simple' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:incall' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:in block in call' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:ineach' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:502:in call' /var/lib/gems/2.1.0/gems/activesupport-4.2.3/lib/active_support/callbacks.rb:88:inrun_callbacks' /var/lib/gems/2.1.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/reloader.rb:83:in prepare!' /var/lib/gems/2.1.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/reloader.rb:55:inprepare!' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application/finisher.rb:50:in block in <module:Finisher>' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:30:ininstance_exec' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:30:in run' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:55:inblock in run_initializers' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/initializable.rb:54:in run_initializers' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:352:ininitialize!' /home/luca/cmonrails/cmonrails/config/environment.rb:5:in <top (required)>' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:328:inrequire' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:328:in require_environment!' /var/lib/gems/2.1.0/gems/railties-4.2.3/lib/rails/application.rb:457:inblock in run_tasks_blocks' Tasks: TOP => db:migrate => environment (See full trace by running task with --trace)

RubyZip fails - closed stream

I have a chef-cookbook with following ruby code:

    class Chef::Recipe::Helpers
      def self.is_config?(filename)
        ['.lua', '.conf'].include?(File.extname(filename))
      end

      def self.out_filename(filename)
        File.extname(filename) == '.conf' ? 'nginx.conf' : filename
      end

      def self.unzip(data, dest_dir)
        ::Zip::File.open_buffer(data) do |fzip|
          fzip.each do |entry|
            next unless is_config?(entry.name)
            content = fzip.read(entry)
            filename = out_filename(entry.name)
            path = File.join(dest_dir, filename)
            File.write(path, content)
          end
        end
      end
      def self.fetch_from_url(url, dest_dir)
        response = HTTPClient.get(url, follows_redirect: true)
        if response.status == 200
             unzip(response.body, dest_dir)
        else
             raise 'Could not fetch files from 3scale'
         end
        end

I have a zip file in an artifact repository that is zipped and uploaded and I give that endpoint for this code to receive in :

ruby_block 'fetch configuration files from a URL' do
    block do
      Helpers.fetch_from_url(node['3scale']['config-url'], version_dir)
    end
    action :run
  end

and this uses the helper function mentioned in the post, but when I run it I get the following error:

 * ruby_block[fetch configuration files from a URL] action run
================================================================================
Error executing action `run` on resource 'ruby_block[fetch configuration files from a URL]'
================================================================================


IOError
-------
closed stream


Cookbook Trace:
---------------
/var/chef/cache/cookbooks/dj-chef-3scale/libraries/default_helper.rb:23:in `block (2 levels) in unzip'
/var/chef/cache/cookbooks/dj-chef-3scale/libraries/default_helper.rb:21:in `block in unzip'
/var/chef/cache/cookbooks/dj-chef-3scale/libraries/default_helper.rb:20:in `unzip'
/var/chef/cache/cookbooks/dj-chef-3scale/libraries/default_helper.rb:34:in `fetch_from_url'
/var/chef/cache/cookbooks/dj-chef-3scale/recipes/default.rb:79:in `block (2 levels) in from_file'


Resource Declaration:
---------------------
# In /var/chef/cache/cookbooks/dj-chef-3scale/recipes/default.rb

 77:   ruby_block 'fetch configuration files from a URL' do
 78:     block do
 79:       Helpers.fetch_from_url(node['3scale']['config-url'], version_dir)
 80:     end
 81:     action :run
 82:   end
 83: elsif mode == 'local'



Compiled Resource:
------------------
# Declared in /var/chef/cache/cookbooks/dj-chef-3scale/recipes/default.rb:77:in `from_file'

ruby_block("fetch configuration files from a URL") do
  action [:run]
  retries 0
  retry_delay 2
  block_name "fetch configuration files from a URL"
  cookbook_name "dj-chef-3scale"
  recipe_name "default"
  block #<Proc:0x0000000420e230@/var/chef/cache/cookbooks/dj-chef-3scale/recipes/default.rb:78>
end

Not sure why I would be getting 'closed stream' here ?

Ruby Watir Unsure what the PageObject is

I am trying to click on a PageObject using watir but i am unsure what the pageobject is called i have tested nearly all of them.

<details open>
    <summary>Search your employers</summary>

This is what is displayed when I have clicked on the pageobject but if I havent clicked it yet it says

<details>
    <summary>Search your employers</summary>

I know how to make the script click on the pageobject but i just dont know what this pageobject.

Im guessing that I would identify it by calling [pageobject](:test, :name => 'Search your employers')

Conditional nested form with simple_fields_for

I have a problem with creating two different forms with one model on one page. I tried two different approaches. Neither of them works.

Approach one:

Models:

class User < ActiveRecord::Base
  belongs_to :report

  ADMIN = 0
  NORMAL = 1
end

class Report < ActiveRecord::Base
  has_many :users
  has_many :normal_users, class_name: 'User', condition: {kind: User::NORMAL}
  has_many :admin_users, class_name: 'User', condition: {kind: User::ADMIN}
end

Approach 2 (Single Table Inheritance):

class User < ActiveRecord::Base
  belongs_to :report
end

class NormalUser < User
end

class AdminUser < User
end

class Report
  has_many :users
  has_many :normal_users
  has_many :admin_users
end

The problem:

simple_fields_for can see :users association:

= form_for @report do |f|
  = f.simple_fields_for :users do |ff|
    = ff.input :field_1
    = ff.input :field_2
  = f.submit 'Save'

But can't neither of :normal_users and :admin_users in both approaches.

= form_for @report do |f|
  = f.simple_fields_for :normal_users do |ff|
    = ff.input :field_1
    = ff.input :field_2
  = f.submit 'Save'

= form_for @report do |f|
  = f.simple_fields_for :admin_users do |ff|
    = ff.input :field_1
    = ff.input :field_2
  = f.submit 'Save'

By 'can't see' I mean you can write anything instead if :normal_users or :admin_users and the result is the same - one new record built like the association would not exist.

For now I can see only one option: To physically separate AdminUser and NormalUser by creating respective tables.

Are there other options. Where is the problem with conditional nested association within a form?

rails version 3.2.22

simple_form version 1.5.2

mercredi 24 février 2016

Cloud 9 & Rails: Cannot GET /dev_focus/focus/rails/mailers/user_mailer/account_activation

I am following through with the Rails Tutorial by Michael Hartl but have come to a bump in the road when trying to preview my mailers using the Cloud 9 IDE.

Here is my user_mailer.rb

class UserMailer < ApplicationMailer

def account_activation(user)
   @user=user
   mail to: user.email, subject: "Activate your focus. account"
end

def password_reset
  @greeting = "Hi"

  mail to: "to@example.org"
end
end

My problem is when I attempt to preview my mailers using the link

http://http://ift.tt/1oINnud/rails/mailers/user_mailer/account_activation

I get a blank page with the following error:

Cannot GET /dev_focus/focus/rails/mailers/user_mailer/account_activation

Any Ideas?

Thanks for your help!

How to append a character at the end of string?

I have a string foo: I want to append a character at the end of a string [ So the final output should be foo: [

I tried the following code.

puts 'foo: ' << '[' & puts 'foo: ' + '['

But both are appending the character in a new line & giving me the following output.

foo: [

However, I want to append the character in the same line & want the below output:

foo: [

Select nth rails record from huge set

We have tens of millions of records in our User model. Our CEO wants to know who every single n-millionth user is. I'm trying to find a performant way to do this.

If I were trying to do find the 10 millionth record, I've tried to do

User.select(:id).where(deleted_at:nil)[9999999]

and

User.find(User.last.id - User.where(deleted_at:nil).count + 9999999)

I've tried to monkey patch the find_nth method from finder methods, but that hasn't worked in a performant way as well.

I get that "performant" may be a stretch, but I'm interested in the most efficient way to do this. Any suggestions?

How to print previous line if the current line meet the condition?

I am reading some data from file in the following way.

File.foreach(input_file) do |line|
   # Do Something with each Line
   puts line
   puts line.inspect
end

The get the following output.

helloworld:
prodValue:
version:7
class:[
ratio:
value: ""
stackOverflow:
version:3

#Inspect Output
"helloworld:"
"prodValue:"
"version:7"    
"class:["
"ratio:"
"value: """
"stackOverflow:"
"version:3"

I want to fetch previous line if the next_line.include? 'version:'. For instance, in the above case I want to print prodValue: & StackOverFlow:

Could you please help me with the solution?

Mysql2::Error: Can't connect to MySQL server on '127.0.0.1' on heroku push

When i do git push heroku master ,it fails at rake assets precompile and i get an error Mysql2::Error: Can't connect to MySQL server on '127.0.0.1' heroku

What i already know Since i am using Rails 4,Definitely config.assets.initialize_on_precompile = false is out of the picture because is no longer required.

heroku labs:enable user-env-compile this feature is no longer supported by Heroku.

After doing research online, I learned that the solution might be here heroku build pack But i don't understand how to run those commands. I keep getting bash: bin/compile: No such file or directory

How do i resolve this issue? I am using Rails 4.2.5 ,Ruby 2.3.0 and the Db is Mysql locally.Thank you in advance.

Call a rails 3 controller action after server startup

We have a rails 3 controller action that calls a remote api & caches the response. Unfortunately it's a slow process, so the first person to call that action has to wait quite a long time for the response. How can I call this controller action when rails starts (or at some point soon after) so the first user does not have to have that long delay.

Thanks in advance

how to access child new form from parent index page in rails?

I am trying to fetch booking controller's new form, from the cab index page. how can i fetch it? how can access the new form from cab index page where i have shown all the cabs which are added..

cab controller

    class CabsController < ApplicationController


before_action :find_cab, only: [:show, :edit, :update, :destroy]

def index
    @cabs = Cab.all.order("created_at DESC")
end

def new
    @cab = Cab.new
end

def show
    @reviews = Review.where(cab_id: @cab.id).order("created_at DESC")

    if @reviews.blank?
      @avg_review=0
    else
      @avg_review=@reviews.average(:rating).round(2)
    end
end

def edit
end

def create
    @cab = Cab.new(cab_params)
    if @cab.save
        redirect_to @cab
    else
        render 'new' 
    end
end

def update
    if @cab.update(cab_params)
        redirect_to @cab
    else
        render 'edit'
    end
end

def destroy
    @cab.destroy

    redirect_to root_path
end

private

def find_cab
    @cab = Cab.find(params[:id])
end


def cab_params
    params.require(:cab).permit(:name, :number_plate, :seat, :image)
end 
end

booking controller

    class BookingsController < ApplicationController

before_action :find_booking, only: [:show, :edit, :update, :destroy]
before_action :find_cab

def index
 @bookings = Booking.where(cab_id: @cab.id).order("created_at DESC")
end

def new
 @booking = Booking.new
end

def show
end

def edit
end

def create
  @booking = Booking.new(booking_params)
  @booking.user_id = current_user.id
  @booking.cab_id = @cab.id

  if @booking.save
   redirect_to cab_booking_path(@cab, @booking)
 else
   render 'new'
 end
end

def update
end

def destroy
end

private

def find_booking
  @booking = Booking.find(params[:id])
end

def find_cab
  @cab = Cab.find(params[:cab_id])
end

def booking_params
  params.require(:booking).permit(:date, :address, :start_destination, :destination, :start_date, :end_date, :contact_no)
end

end

routes

     resources :cabs  do
       resources :bookings
     end

cab/index.html.erb

    <div class="container">
<h2>All Cabs</h2>
<div class="row">


    <% @cabs.each do |cab| %>
        <div class="col-sm-6 col-md-3">
            <div class="thumbnail">
                <%= link_to image_tag(cab.image.url(:medium), class: 'image'), cab %><br>
                Cab Name : <h4><%= cab.name %></h4>
                <%= link_to "Book Now", new_cab_booking_path(@cab, @booking) %> # i wanted to create this link
            </div>
        </div>
    <% end %>
</div>
<%= link_to "Add Cab", new_cab_path, class: 'btn btn-default' %>

the error i am getting is

    No route matches {:action=>"new", :cab_id=>nil, :controller=>"bookings"} missing required keys: [:cab_id]

Server don't work ruby on rails at Neatbens 8.0.2

i have neatbens 8.0.2 and I load a proyect of ruby on rails. The version of ruby its 1.8.7 and rails 2.3.5. When play the server output

./script/../config/../config/preinitializer.rb:5: Could not load the bundler gem. Install it with gem install bundler. (RuntimeError) from ./script/../config/boot.rb:28:in load' from ./script/../config/boot.rb:28:inpreinitialize' from ./script/../config/boot.rb:10:in boot!' from ./script/../config/boot.rb:114 from script/server:2:inrequire' from script/server:2

I put 127.0.0.1/3000 in chrome and dont see nothing.

Export csv in activeadmin new page(no model)

I have created new page in active admin as details in my new page I want to display the table which is having data from another model(miles), Problem is I want to export all data to csv form? Check the following code I'm facing problem with exporting..

 ActiveAdmin.register_page "Details" do
menu false
  page_action :csv, method: :get do
     # transactions = Transaction.all.page(params[:page]).per(Transaction::ADMIN_PAGE_LIMIT) 
               @milestones =  Milestone.all
      @collection =  @milestones.select{|a| a.milestone_status == false}
      @month_collection = @collection.select{ |a| a.delivery_date.to_date.strftime('%m%Y') == Date.today.strftime('%m%Y') }
     transactions = @month_collection
     csv = CSV.generate( encoding: 'Windows-1251' ) do |csv| 
     # add headers 
     csv << ["admin_user", "project", "client", "milestone_name", "delivery_date", "milestone_payment", "received_amount"] 
     transactions.each do |transaction|
      csv << [ transaction[:admin_user], transaction[:project], transaction[:milestone_name], transaction[:delivery_date], transaction[:milestone_payment], transaction[:received_amount]] 
         end 
     end
      # send file to user 
      send_data csv.encode('Windows-1251'), type: 'text/csv; charset=windows-1251; header=present', disposition: "attachment; filename=transactions_#{DateTime.now.to_s}.csv" end
       action_item do
        link_to "Export to CSV", method: :get 
    end 
end

mardi 23 février 2016

How to update status value in table on each button click

i want to update status value in property table as (1 or 2 or 3 or 4) on click on each button

these are my buttons in my view file.

<td><%= link_to("Waiting for Response", rms_property_approve_property_path(property, {:status => 'Waiting for Response'}), method: :patch, class: "btn btn-success", "data-no-turbolink" => true) %><td> <td><%= link_to("No Response", rms_property_approve_property_path(property, {:status => 'No Response'}), method: :patch, class: "btn btn-danger", "data-no-turbolink" => true) %><td> <td><%= link_to("Registered", rms_property_approve_property_path(property, {:status => 'Registered'}), method: :patch, class: "btn btn-success", "data-no-turbolink" => true) %><td> <td><%= link_to("Not Interested", rms_property_approve_property_path(property, {:status => 'Not Interested'}), method: :patch, class: "btn btn-danger", "data-no-turbolink" => true) %><td>

My propertiescontroller.rb

def approve @property = Property.find(params[:property_id]) if params[:status]== 'Registered' @property.update_attributes(:status => 1) redirect_to :back, flash: {notice: "Property has been Registered."} elsif params[:status]== 'Not Interested' @property.update_attributes(:status => 2) redirect_to :back, flash: {notice: "Not Interested."} elsif params[:status]== 'Waiting for Response' @property.update_attributes(:status => 3) redirect_to :back, flash: {notice: "Waiting for Response"} elsif params[:status]== 'No Response' @property.update_attributes(:status => 4) redirect_to :back, flash: {notice: "No Response."} end end

my status column on property table

class AddColumnStatusInProperties < ActiveRecord::Migration def change add_column :properties, :status, :string end end

Here i clicked on No response button, but i'm getting this error on executing this. Any solution.

Any Help is appreciatable.

enter image description here

Chartkick in Ruby on Rails Loading

Using chartkicks for showing pie_charts. On simple html.erb it works properly.BUt I want to show it in PDF.For it use wicked-pdf. When I laod page pie-chart not showing only loading.

app/layout/pdf.html.erb

<!doctype html>
<html>
<head>
<meta charset='utf-8' />

<%= wicked_pdf_stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
<%= wicked_pdf_javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= javascript_include_tag "http://ift.tt/zYvreR"%>
<%= wicked_pdf_javascript_include_tag 'chartkick'%>
</head>
<body onload='number_pages'>
<div id="header">
  <h2>Report</h2>
</div>
<div id="content">
  <%= yield %>
</div>
</body>
</html>

app/views/report/survey.pdf.erb

<div>
<%= pie_chart({"Football" => 10, "Basketball" => 5}) %>
</div>

Implement add Recipe to favorites in Rails and find if current user has 'favorite_set?' a recipe

This question is related to that shows a has_many :through association. I have a similar association as shown in the answer. I will cite for reference.

$ rails g model FavoriteRecipe recipe_id:integer user_id:integer

# Join model connecting user and favorites
class FavoriteRecipe < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :user
end

---

class User < ActiveRecord::Base
  has_many :recipes

  # Favorite recipes of user
  has_many :favorite_recipes # just the 'relationships'
  has_many :favorites, through: :favorite_recipes, source: :recipe # the actual recipes a user favorites
end

class Recipe < ActiveRecord::Base
  belongs_to :user

  # Favorited by users
  has_many :favorite_recipes # just the 'relationships'
  has_many :favorited_by, through: :favorite_recipes, source: :user # the actual users favoriting a recipe
end

I am curious to know if this solution would work with a many-to-many relationship with joining model e.g. FavoriteRecipe that has a boolean attribute favorite_set. When iterating through the Recipes I would like to find out if the current user has 'favorited' this/these Recipes. Something like current_user.recipe.favorite_set? but of course going through the FavoriteRecipe joining model. If true display 'FAVORITE SET' otherwise give an option to favorite this recipe. My implementation is a feed that displays all "Recipes" and shows "FAVORITE SET" or gives the option to "favorite" one or multiple Recipes.

Thanks in advance.

Create hash from string

I have hash like this input: { "token" => "09d43089eef82b25eac082b50567512a566e4d2b", "quote{insurance_type_id" => 1, "quote{period_id" => "1", "quote{period_id" => 1, "quote{items[0{vehicle_id" => "203972", "quote{items[0{vehicle_manufacture_year" => 2012, "quote{items[0{drivers[0{driver_type_id" => 1, "quote{items[{drivers[1{driver_type_id" => "1" } and i want to out put like this output: quote: { items: [ { drivers: [ {driver_type_id: 1}, {driver_type_id: 2} ] } ] } please help me how can i do that.

copy contents of a remote location to a local file in ruby script

I want to copy the contents of a remote location file to some local file after an ssh connection has been made.

 begin
    ssh = Net::SSH.start("localhost", "user")
    logger.info "conn successful!"
    results = conn.exec!('ruby somefile "#{arguments}"')
    #code to copy the contents of a.txt in remote location to local file
    #IO.copy_stream (localfile, remotefile)
 rescue
    logger.info "error - cannot connect to host"
 end

I tried using IO.copy_stream but that doesn't work. How do I go about this?

Email Validation with Regex for Ruby on Rails [duplicate]

This question already has an answer here:

I want to validate the input email as right format. This is my current code in the model:

EMAIL_REGEX = /\A[^@]+@([^@\.]+\.)+[^@\.]+\z/
validates :email, :format => {:with => EMAIL_REGEX}, :uniqueness => {case_sensitive:false}

This works fine. However, since the email address is not required. User don't necessarily need to input anything. How can I allow the situation that user let the field blank?

Rails - Not equal in Active Record

I want to execute a sql query against a table. I'm experiancing a problem in which I cannot proceed.

How can I use Active Record to query a table where column is not equal to null? Current query is given below but it's not working as it gives me a null.

no_sweets = CookieJar.where(cookie_id: array_of_cookies, artificial_sweetner: !nil).count

I want to get count of sweets whose id's are included in array_of_cookies and artificial_sweetner is not null.

Below code works just fine but I need it in Rails way or say I'll need objects to manipulate.

no_sweets = CookieReportingDb.connection.execute("SELECT count(*) FROM cookie_db_new.cookie_jars where artificial_sweetner is not null and cookie_id IN (#{array_of_cookies.join(', ')})").first

I'm using ruby 1.9 and Rails 3.2.

Mail sent twice or more instead of once using rails 3.2

I am working with rails 3.2 and ruby 2.1.2p95. Through my application, sending 1000+ of emails. I want to send few email from smtp and few emails from sendgrid. So I have configured like below in Notifier.rb file

after_filter :set_delivery_options, :except => [:method1]

def set_delivery_options message.delivery_method.settings.merge!(:address => "smtp.gmail.com", :port => 587, :domain => "xxxxxxxx", :user_name => "xxxxxxxxxxxxx", :password => "xxxxxxxxxxxxx", :authentication => "plain", :enable_starttls_auto => true) end

My method is like below:

def method1(customer) mail( :to => customer.user.email, :subject => "Testing", #:bcc => EMAIL_BCC, :content_type => "text/html" ) end

Whenever I call the above method, the mail is sending twice or more in some times on production server.

how to put 3 in a list by using .each

I have this code

<ul id="mycarousel-1" class="jcarousel-skin-tango">
  <% @portfolios.each_slice(3) do |f| %> 
    <li><% @portfolios.each do |f| %> 
     <%= link_to image_tag(f.image.url(:medium)), image_path(f.image.url()),class: "plus"  %>
  <% end %>
</ul>

How can I put each 3 image in a one list

CanCan::AccessDenied: You are not authorized to access this page. Rails

While performing Unit Test using Rake on my Rails4 application, where I have used CanCan, It is giving me an access denied error while testing the index. The application is running fine, dont know how to test the index. Kindly, help me out in this one. Thanks in advance.

FittingsurveysControllerTest Error :-

FittingsurveysControllerTest#test_should_get_index:
CanCan::AccessDenied: You are not authorized to access this page.
test/controllers/fittingsurveys_controller_test.rb:15:in `block in <class:FittingsurveysControllerTest>'

fittingsurveys_controller_test.rb

test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:fittingsurveys)
end

Application Controller -

 def access_denied(exception)
    redirect_to new_user_session_path, :alert => exception.message
end

Config/initializers/rails_admin.rb

RailsAdmin.config do |config 
config.authorize_with :cancan
config.current_user_method &:current_user

Fittingsurveys_controller.rb

class FittingsurveysController < ApplicationController
before_action :set_fittingsurvey, only: [:show, :edit, :update, :destroy]
before_filter :capture_referrer
load_and_authorize_resource
respond_to :html
def index
@fittingsurveys = Fittingsurvey.all
respond_with(@fittingsurveys)
end

app/models/ability.rb

class Ability
include CanCan::Ability
def initialize(user)
def initialize(user)
can :read, :all 
can [:new,:create,:show,:update], [Fittingsurvey,UserFeedback]
cannot :index,[Fittingsurvey,User]

if user && user.role.name=="ADMIN"
can :manage, :all
can :access, :rails_admin
can :export, :all
can :manage, :all
can :manage, User
can :index, [Fittingsurvey,User,UserFeedback]
cannot :index,[Address,Fittingblackout]
end
end
end

amazon s3 give image path with additional query string

I 'm using Paperclip to upload Images to Amazon S3 in Ruby on Rails. Its working fine, Images save & display well But the url is Like

http://ift.tt/24n36PC I want to know that how this query ?1456223556 string appended in path Is it happening due to S3 or something I 've done in Code

How to run rails console on google cloud using GNU Screen?

I have installed Screen on my google cloud server. I would like to run a program through rails console using screen, but I cannot figure out how to do this. Can anyone provide a step by step process (or point me to a link) on how to do this? Thanks.

lundi 22 février 2016

Rails 3.2 - mail not sending

I've got a mailer class in Rails 3.2 that refuses to send mail, giving the following error:

Outgoing message to devs: #<Mail::Message:98270300, Multipart: false, Headers: <From: no-reply@example.com>, <To: dev@example.com>, <Subject: Error with script>, <Mime-Version: 1.0>, <Content-Type: text/html>>

rake aborted!

At least one recipient (To, Cc or Bcc) is required to send a message

... yet the to field clearly has a recipient!

Here's my mailer class:

class Notifier < ActionMailer::Base
  def send_mail_to_developer(error)
    @error = error
    mail to: "dev@example.com", subject: "Error with script"
  end
end

Here's my rake task:

begin
  task :import_bars
    begin
      Foo.import_foos
    rescue => e
      mail = Notifier.mail_current_developers(error)
      puts "Outgoing message to devs: #{mail.inspect}"
      mail.deliver!
    end
  end
end

This seems just so curly so I'm not sure what to do or why this error is occurring. Help?

SSL-Error Rails 3 only with passenger

I have a problem with Rails 3 and Passanger accessing the paypal api. Everything is OK on the rails console, but when I access the site with passenger I get this error (live not paypal sandbox):

App 14160 stderr: Action: SetExpressCheckout App 14160 stderr: Request[post]: http://ift.tt/Sy2ioq Completed 500 Internal Server Error in 378.0ms

OpenSSL::SSL::SSLError (SSL_connect returned=1 errno=0 state=SSLv3 read server hello A: sslv3 alert handshake failure)

Has anyone had a problem like that? Ruby and Rails are the same version for passenger.

Ruby on Rails check that multiple values aren't blank or equal to each other

I have a form in a ruby on rails site that takes in a bunch of different parameters. I want to ensure that none of these parameters equal each other IF they are not blank. With how the form is designed, none of these values are required, so some of them can be blank. I can do this with a conditional statement of course, but I wanted to ensure whether or not there is a cleaner way to do so as the conditional statement would be HUGE with all of those checks. Again, if any of the values are equal to each other when (and only when) those values are chosen, I want to return an error that they can not be equal. The values are chosen by collection_select controls, so I'm not seeing any way to filter out duplicates beforehand. Is there a more concise way to compare all of these values?

if ((value1 == value2) && !value2.blank?) || 
   ((value1 == value3) && !value3.blank?) ||
   ((value1 == value4) && !value4.blank?) ||
   .... 
   ((value9 == value10) && !value10.blank?))
    Do error stuff
else
    Behave normally
end

ActionView::Template::Error: undefined method `split' for nil:NilClass

i am getting for above error. i can't find the solution. pls tell me.

this is my feed_view_mobile.erb code;

if params[:controller]=='categories'
    meta :title => " #{feed_hash[:filter_keyword]+' | ' if feed_hash[:filter_keyword].present?} " + (feed_hash[:seo_title]||feed_hash[:title]) + ( ((' - Page ' + params[:page]) if params[:page].present?) ||''),
    :description => " #{feed_hash[:filter_keyword]+' | ' if feed_hash[:filter_keyword].present?} " + (feed_hash[:description] || '') + ( ((' - Page ' + params[:page]) if params[:page].present?) ||''),
    :keywords => (feed_hash[:filter_keyword].split.select{ |x| x.length>2}).concat(feed_hash[:keywords] || feed_hash[:title].split.select{ |x| x.length >2 })
    #salwar special case for testing.
    @secondary_message = "<a class='btn btn-primary btn-attn' href='"+new_user_registration_path.to_s+"'>Signup </a>" + "  and get your free personal stylist." if !current_user.present? && params[:term]!="salwars-churidars"
    @secondary_message = ""
end

dimanche 21 février 2016

How to solve undefined local variable or method error

i have three tables, RM, GenericUser and Properties.

RM fields :id, name

generic_users fields are: id,mobile,rm_id,name.

Properties fields are: id,image,rm_id,generic_user_id,property_name.

RM is creating GenericUsers,so that rm_id automatically entered in Generic Users table.

After that generic user logs in and creates property,so when generic user creates property,rm_id should fetch from generic user table and should enter in property table field where rm_id is there.

i have model relation like this.

class Rm < ActiveRecord::Base acts_as :user has_many :generic_users end

class Property < ActiveRecord::Base belongs_to :generic_user end

class GenericUser < ActiveRecord::Base belongs_to :rm has_many :properties end

my generic_users propertiescontroller

def create @property = Property.new(property_params) @gu=GenericUser.select(:rm_id).where(:id=>current_user.specific.id) @property.rm_id=@gu.rm_id logger.info @property.rm_id.inspect if @property.save redirect_to :back, notice: 'Property was successfully created.' else render :new end end

i am getting this error enter image description here

Please help if any idea. Any help is appreciatable

Updating master product Spree Rails api

To update a product using Spree API we have to make a request like:

PUT /api/products/a-product?product[name]=Headphones

This works for me the product is updated, but when I pull the product through API, the name for product is updated but not that for the master.

Then I tried something like this:

PUT /api/products/ruby-on-rails-tote/variants/2?variant[sku]=12345

thinking master might be a variant itself, but this does not update the master product. Am I doing something wrong here? What's the correct way to update the master of a product in a Spree store through API calls?

private method `update_without_password' called for nil:NilClass

I am following this tutorial on cancancan authentication, and specifically wanting admins to update users without needing a password. I've also seen this suggestion, but am unsure how to adapt it into my own code. When I click update, it says 'NoMethodError in UsersController#update' private method `update_without_password' called for nil:NilClass

My app returns all the user's params, so I don't understand what's happening here. Still very new to rails - let me know if you need any further information. Thank you in advance!

USERS CONTROLLER

class UsersController < ApplicationController
before_filter :authenticate_user!



 def update
  if user_params[:password].blank?
    user_params.delete(:password)
    user_params.delete(:password_confirmation)
  end


  successfully_updated = if needs_password?(@user, user_params)
                           @user.update(user_params)
                         else
                           @user.update_without_password(user_params)
                         end
 respond_to do |format|
    if successfully_updated
      format.html { redirect_to @user, notice: 'User was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { render action: 'edit' }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end


  rescue ActiveRecord::RecordNotFound
    respond_to_not_found(:js, :xml, :html)
  end


private
def needs_password?(user, params)
  params[:password].present?
end

def update_without_password(user_params)
  user.update_without_password(user_params)
end



def user_params
        params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :name, :role_id, :accepted)
end

EDIT FORM

<h3><%= @user == @current_user ? "Your Account Settings" : "Edit User" %></h3>

<%= form_for(@user, :html => { :method => :put }) do |f| %>
 <p><%= f.label :first_name %></p>
 <p><%= f.text_field :first_name %></p>

 <p><%= f.label :last_name %></p>
 <p><%= f.text_field :last_name %></p>

 <p><%= f.label :email %></p>
 <p><%= f.text_field :email %></p>
  <% if can? :read, Role %>
 <%= collection_select(:user, :role_id, Role.all, :id, :name, {prompt: true}) %>
  <% end %>
 <p><%= f.submit "Update" %></p>
<% end %>

What am I missing here? Please let me know if should provide anything else. Thanks!!

Create multiple relationships

I am developing a Q&A app and the thing is, I want to add the ability for people to post answers.

I already built a migration so that the question has the same id of the user with rails g migration add_user_id_to_questions and then added the has_many/belongs_to

Now I am stuck with how to create a relationship for the answers.

I already added a answer scaffold with: rails g scaffold Answer answer:integer

And then I did a migration: (Was it a right move? to create a migration so that answers have the same ID as the question?)

rails g migration add_answer_id_to_answers

And added the has_many/belong_to as well.

But now what? How do I make answer the to have the same ID of the question? Because inside the show view, if a user posts an answer it will basically be visible on every question...

Show view:

      <% @answers.each do |answer| %>

      <div class="well bgBlack">
          <div class="media">
            <a class="pull-left">
            <% if answer.user.avatar.blank? %>
                <img src="http://ift.tt/2176wHd" style="width: 75px;">
            <% elsif answer.user.avatar %>
                <%= image_tag answer.user.avatar, :style => "width:75px;" %>
            <% end %>
            </a>
            <div class="media-body">
              <p class="white"><%= link_to answer.user.username, answer.user, :class => " bg" %></p>
              <p class="white small"><%= answer.answer %></p>
           </div>
           <div class="pull-right">
                <% if user_signed_in? %>
                    <% if answer.user_id == current_user.id %>
                        <%= link_to 'delete', answer_path(answer), :method => :delete, :class => "text-muted white" %>
                    <% end %>
                <% end %>
           </div>
        </div>
      </div>                

      <% end %>

User model:

class User < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader
  has_many :questions, :dependent => :destroy
  has_many :answers, :dependent => :destroy

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

Question model:

class Question < ActiveRecord::Base
    belongs_to :user
    has_many :answers
end

Answer model:

class Answer < ActiveRecord::Base
    belongs_to :user
    belongs_to :question
end

Answer controller:

class AnswersController < ApplicationController
  before_action :set_answer, only: [:destroy]

  respond_to :html

  def create
    @answer = current_user.answers.build(answer_params)
    @answer.save
    redirect_to :back
  end

  def destroy
    @answer.destroy
    redirect_to :back
  end

  private
    def set_answer
      @answer = Answer.find(params[:id])
    end

    def answer_params
      params.require(:answer).permit(:answer)
    end
end

Cannot modify association 'User#roles' because the source reflection class 'Role' is associated to 'Profile' via :has_many

I have three models, a user, a profile and a role, where I'm trying to attach multiple roles to a user through profile.

# user.rb
class User < ActiveRecord::Base
  has_one :profile, dependent: :destroy
  has_many :roles, through: :profile
  has_many :interests, through: :profile
  has_many :industries, through: :profile
end

# profile.rb
class Profile < ActiveRecord::Base
  has_one :user, dependent: :destroy
  has_many :roles
  has_many :interests
  has_many :industries
end

# role.rb
class Role < ActiveRecord::Base
  has_many :profiles
  has_many :users, :through => :profiles
  has_many :users
end

I'm trying to use the following in edit.html.erb (simple_form_for)

<%= f.association :roles,
                   as: :check_boxes,
                   label_method: :name,
                   value_method: :id,
                   label: 'Roles' %>

With the following params

params.require(:user).permit([:email, :first_name, :last_name, :admin, :password, role_ids: [] ])

My edit/update method:

  # GET /users/1/edit
  def edit
    @user.build_profile if @user.profile.nil?
  end

  def update
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

Gives me the following error message

Cannot modify association 'User#roles' because the source reflection class 'Role' is associated to 'Profile' via :has_many.

I've been looking at the problem for hours, but I can't seem to find the mistake.

samedi 20 février 2016

How to resolve ambiguity error in Rails? Undefined method '_index_path'

Rails convention urges everyone to name models, controllers and other things the way they are named in real life.

I've run into a problem, where my form can't recognize the right form of instance variable.

I have Fish model and corresponding fish controller.

class FishController < ApplicationController
  def index
    @fish = Fish.new
  end
end

Then when I get on my form, I get the error.

<%= form_for @fish do |f| %>
  <%= f.label :type %>
  <%= f.text_field :type, class: "form-control" %>
<% end %>

enter image description here

How can I resolve the issue? Thanks in advance.

Rails 4+ Edit multiple objects in one form BEST PRACTICE

I have a User, Drinks, Gyms, Foods Model.

class User < ActiveRecord::Base
 has_many :drinks
 has_many :foods
 has_many :gyms
end

I track the number of drinks a user had during the day and save it in the database.I do the same with Foods and Gyms.

I have a User and a Session (for login) controller. So far I haven't needed a controller for my "passiv" Models (Drink, Food, Gym).

Now I have one page with a form on which the User can change the entries of all tables(Drink, Food, Gym) of the previous day.

I think I need to use fields_for in the form to edit objects of multiple Models in one form.

However I don't know how many controllers I need and where I should put in all the business logic... I don't want to do anything quick and dirty, but rather follow certain Best Practices.

My approach so far:

  • A lot of forms on one page

    <%= form_for :running, url: data_update_user_path do |f| %>
    <%= form_for :drinks, url: data_update_user_path do |f| %>
    <%= form_for :food, url: data_update_user_path do |f|
    
    
  • One DataController who handles all the different updates (It's basically a big if elsif)

    class DataController 
     def update
    
      if params[:drinks]
       #update drinks
      elsif params[:foods]
       #update foods
      elsif params[:gyms]
       #update gyms
      end
     end
    end
    
    


So my question: What is the best practice in such a situation?

How to pass an :id to a link_to through a has_many :through relationship to delete a join table column. (Rails)

This is my first post on StackOverflow, and I'm relatively new to coding in general, so I apologize in advance if I accidentally make some breach of etiquette.

I'm trying to delete a collaborator to a wiki that has been added by the owner, but now he wants to remove their permissions.

This is done from within my wiki#edit view:

<div class="row">
<%= render partial: 'wikis/form' %>
<br>
<%= render partial: 'collaborators/collaborator'%>

<h3> Collaborators: </h3>
<% @wiki.users.each do |c| %>
  <li><%= c.username %></li>
  <% if @wiki.user == current_user && current_user.premium? %>
    <%= link_to "", wiki_collaborator_path(@wiki, @collaborators), method: :delete, remote: true, class: "glyphicon glyphicon-remove"  %>
  <% end %>
<% end %>

The wikis/_form partial is pretty standard:

<div class="col-md-8">

<div class="form-group">
  <%= f.label :title %>
  <%= f.text_field :title, class: 'form-control', placeholder: "Enter wiki title" %>
</div>
<div class="form-group">
  <%= f.label :body %>
  <%= f.text_area :body, rows: 8, class: 'form-control', placeholder: "Enter wiki body" %>
</div>

<% if current_user.admin? || current_user.premium? %>
<div class="form-group">
  <%= f.label :private, class: 'checkbox' do %>
    <%= f.check_box :private %> Private wiki
    <% end %>
</div>
<% end %>

<div class="form-group">
  <%= f.submit "Save", class: 'btn btn-primary' %>
</div>
  <% end %>
</div>

and the collaborators/_collaborator partial creates the initial collaborator:

 <% if @wiki.user == current_user && current_user.premium? %>
  <%= form_for [@wiki, Collaborator.new] do |f| %>
  <%= email_field_tag :collaborator %>
  <%= f.submit "Add collaborator", class: 'btn btn-primary' %>
  <% end %>
<% end %>

This is the Collaborator controller:

  before_action :set_wiki
  def create
    @collaborator = User.find_by_email(params[:collaborator]) #pulled from email tag in collaborator form_for partial
    Collaborator.create(user_id: @collaborator.id, wiki_id: @wiki.id)

    if @collaborator.save
       flash[:notice] = "#{@collaborator.username} at #{@collaborator.email} has been added as a collaborator to #{@wiki.title}"
    else
       flash[:error] = "Adding of collaborator failed"
    end
    redirect_to @wiki
  end

  def delete
    @collaborator = @wiki.users.find(params[:id])

    if @collaborator.destroy
       flash[:notice] = "#{@collaborator.username} at #{@collaborator.email} has been removed from wiki: #{@wiki.title}"
    else
       flash[:error] = "Removal of collaborator failed"
    end
    redirect_to @wiki
  end
private
  def set_wiki
    @wiki = Wiki.find(params[:wiki_id])
  end
end

The Collaborator Model just belongs_to both User and Wiki, and The Wiki model looks like this:

class Wiki < ActiveRecord::Base
  belongs_to :user
  validates :user, presence: true
 #Final refactoring eliminates need for delegate method
 has_many :collaborators, dependent: :destroy
 has_many :users, through: :collaborators
 scope :visible_to, -> (user) { user ? all : where(private: false) }
  validates :title, length: { minimum: 5 }, presence: true
  validates :body, length: { minimum: 20 }, presence: true
end

The error I'm getting back from my local server is

No route matches {:action=>"destroy", :controller=>"collaborators", :id=>nil, :wiki_id=>"104"} missing required keys: [:id]

I've looked everywhere to solve this problem, but I inherently have some trouble understanding the nested routing for has_many :through associations and when I look for answers it seems like everyone has written their method calls differently than mine. Everything in my app functions except this link_to method, so I'd rather not rewrite it just to match someone else's code unless I really messed up somewhere.

I've tried putting @collaborator.id as well as a few other things just to try to brute force a solution, but nothing is working and I have no idea what I'm looking for here.

Any help at all would be greatly appreciated. Thank you ^^

RAILS API Endpoint

I am a .NET developer and need to work on a API built in Ruby. Following is the API Code. Can anybody help me in getting the endpoint to it.

 class Api::SessionsController < ApplicationController
   respond_to :json
   skip_before_filter :verify_authenticity_token

   before_filter :protect_with_api_key

   def update
     status = true
     participant_ids = []
     unless params[:participants].blank?
       params[:participants].each do |participant_data|
         participant = Participant.where(participant_id:                                  participant_data['participant_id']).first
       unless participant.present?
         status = false
         participant_ids << participant_data['participant_id']
       else
         activity_records = participant_data['cumulative_time']['activity_records']
         participant_data['cumulative_time']['activity_records'] = [] if  activity_records.nil?
         participant.participant_sessions.new(participant_data['cumulative_time'])
         participant.save!
       end
     end
   end 

   if status
     render :json => {status: "OK"}
   else
     render :json => {error: "No participant with id # {participant_ids.join(',')}"}, :status => 422
      end 
   end

 end

I have tried to work with following way /api/sessions/ Pass the required key passing the participant parameter with PUT Request like below

{"participants":[{"first_name":"Demo", "last_name":"User",     "email":"demouser@demouser.com", "password":"RubyNewBie","postal_code":"160055", "coordinator_name":"RubyNewBie", "coordinator_email":"info@RubyNewBie", "coordinator_phone":""}]}

Please guide me.

Thanks and Regards

vendredi 19 février 2016

How to read from a file & store key:value pair in String Array?

I have a coffee script file with the following data in it. I want to create a string array that will store the following data as key:value pair in it.

abTests:
    productRanking:
      version: 4
      groups: [
        ratio:
          default: 1
          us: 0.90
          me: 0.0
        value: "LessPopularityEPC"
      ,
        ratio:
          default: 0
          us: 0.1
        value: "CtrEpcJob"
      ,
        ratio:
          default: 0
          me: 1.0
        value: "RandomPerVisitor"
      ]
    sabt:
      version: 1
      groups: [
        ratio:
          default: 1
          us: 0.90
        value: "default"
      ,
        ratio:
          default: 0
          us: 0.05
        value: "colorBoost"
      ,
        ratio:
          default: 0
          us: 0.05
        value: "colorPriority"
      ,
        ratio:
          default: 0
          us: 0
        value: "noColorClause"
      ]

I want to create a String Array with these data in the following format

productRanking:LessPopularityEPC
productRanking:CtrEpcJob
productRanking:RandomPerVisitor
sabt:default
sabt:colorboost
sabt:colorPriority
sabt:nocolorClause

Is there any way to solve this problem??

set secret keys for amazon aws3

I use fog and carrierwave. Right now I just have simple uploader that I run locally:

CarrierWave.configure do |config|
    config.fog_credentials = {
        :provider               => 'AWS',
        :aws_access_key_id      => ENV['S3_ACCESS_KEY'],
        :aws_secret_access_key  =>  ENV['S3_SECRET_KEY'],
      :region                 => 'us-west-1', # Change this for 

  }
  config.fog_directory  = "bucket-main"    
end

But now I have a question where should I save my secret keys.

On heroku environment I could print like this

$ heroku config:set S3_ACCESS_KEY=THERANDOMKEYYOUGOT  
$ heroku config:set S3_SECRET_KEY=an0tHeRstRing0frAnDomjUnK  
$ heroku config:set S3_REGION=us-west-2  
$ heroku config:set S3_BUCKET=my-sample-app-bucket-20160126

But I don't know what to do on my local machine.

I've followed this tutorial http://ift.tt/1Kvk5J8

And stored my keys in config/secrets.yml file which I just created:

development: &defaults
  S3_ACCESS_KEY: "AKHJJHHJHJJHHJHJDHJDDJDHJDHJDJHDRANDOMFQ"
  S3_SECRET_KEY: "HfkdjgjkfjkgjkfjkRANDOM2JSJDKKJJKSSJDJKSKaN"

test:
  <<: *defaults

# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
  <<: *defaults

But rails s command gives me this error: /home/jonstark/.rvm/gems/ruby-2.3.0@railstutorial_rails_4_0/gems/fog-core-1.35.0/lib/fog/core/service.rb:244:in `validate_options': Missing required arguments: aws_access_key_id, aws_secret_access_key (ArgumentError)

Soo what do I do?