mardi 31 mai 2016

Move one object in collection of objects in rails

Here is the scenario, I have these objects. Let's assume that this is a User:

The object came from:

@user = User.all

User Object

[<#User id: 1, firstname: "John", lastname: "Pond">,<#User id: 2, firstname: "Paul", lastname: "Rich">,<#User id: 3, firstname: "Jasmine", lastname: "Ong">]

How can I move one object up, for example I want to move User.id == 2? The result I want is shown below.

[<#User id: 2, firstname: "Paul", lastname: "Rich">,<#User id: 1, firstname: "John", lastname: "Pond">,<#User id: 3, firstname: "Jasmine", lastname: "Ong">]

undefined method `order' for []:Array

I have the following code where I load the activities for the user based on whether or not they are an admin. Users can only see their own activity feed, whereas admins can see the entire stream. This is a precursor to sharing activity feeds with friends, etc.

  def index
    if current_user?
      @incidents = Incident.find_all_by_user_id(current_user.id).order("created_at desc")
    else
      @incidents = Incident.all.order("created_at desc")
    end
  end

I am getting the above referenced error(undefined method "order" for []:Array). It seems to be the .order reference, but I have checked the rails Guides and it seems to be correct syntax.

Any ideas?

Form_for two referenced models error - Ruby on Rails 4.2.6

i'm practicing Rails, i've created 2 models (User, UserInformation) and created a form with FormHelper and fields_for. I followed this guide http://ift.tt/1x5wybs to make it work, but it doesn't. I just want to have one form that create an user that can have only one UserInformation row, and i want the UserInformation to belong only to one User. I'm stuck on this.. will really appreciate a little bit help, thanks!

Error

This is a screenshot of the error i get

app/models/user.rb

class User < ActiveRecord::Base
  has_one :userinformation
  accepts_nested_attributes_for :userinformation
end

app/models/user_information.rb

class UserInformation < ActiveRecord::Base
  belongs_to :user
end

app/views/users/_form.html.erb

<%= form_for(@user) do |f| %>
  <% if @user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>

      <ul>
      <% @user.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :surname %><br>
    <%= f.text_field :surname %>
  </div>
  <div class="field">
    <%= f.label :email %><br>
    <%= f.text_field :email %>
  </div>
  <% f.fields_for :userinformation do |builder| %>
  <div class="field">
      <%= builder.label :birthdate %><br>
      <%= builder.date_field :birthdate %>
  </div>
  <div class="field">
      <%= builder.label :address %><br>
      <%= builder.text_field :address %>
  </div>
  <div class="field">
      <%= builder.label :city %><br>
      <%= builder.text_field :city %>
  </div>
  <div class="field">
      <%= builder.label :country %><br>
      <%= builder.text_field :country %>
  </div>
  <% end %>
  <div class="actions">
    <%= f.submit "Submit" %>
  </div>
<% end %>

app/controllers/users_controller.rb

class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]

  # GET /users
  # GET /users.json
  def index
    @users = User.all
  end

  # GET /users/1
  # GET /users/1.json
  def show
  end

  # GET /users/new
  def new
    @user = User.new
    @user.userinformation.build
  end

  # GET /users/1/edit
  def edit
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)

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

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  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

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:name, :surname, :email)
    end
end

db/schema.rb

ActiveRecord::Schema.define(version: 20160531152010) do

  create_table "user_informations", force: :cascade do |t|
    t.date     "birthdate"
    t.string   "address"
    t.string   "city"
    t.string   "country"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "user_informations", ["user_id"], name: "index_user_informations_on_user_id"

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.string   "surname"
    t.string   "email"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

How to use devise parent_controller for devise inherited controller but skip for ActiveAdmin devise controller?

I am developing Api based application, site.com (Client App), api.site.com (Server App)

In my api.site.com, there are passwords, confirmations controller, which are inherited from the Devise controllers. By default Devise parent controller is Application controller, but Devise inherited controllers need to pass through ApiBaseController api_authentication action. So, Devise.rb has following configuration:

config.parent_controller = 'ApiBaseController'

Api authentication is working fine now.

ApiBaseController sample code:

class ApiBaseController < ApplicationController
  before_action :api_authentication

  def api_authentication
    api_key = request.headers['Api-Key']
    @app = Application.find_by_api_key(api_key) if api_key
    unless @app
     return render json: { errors: { message: 'Something went wrong, contact admin', code: '1000' } }
    end
  end
end

Now i am using ActiveAdmin, after installing ActiveAdmin i tried to open http://localhost:3000/admin/login on browser, I saw following error response on browser instead of active admin login page:

{"errors":{"message":"Something went wrong, contact admin","code":1000}}

I checked the issue, and i realized that "active_admin/devise/sessions" controller also passed through ApiBaseController. This is because we had set our parent controller to ApiBaseController (config.parent_controller = 'ApiBaseController'). I removed the code and ActiveAdmin worked fine.

But passwords, confirmations controller did not passed through the ApiBaseController api_authentication() since i removed the Devise configuration (config.parent_controller = 'ApiBaseController').

So if you guys have understood the problem, please let me know the solution.

In summary, i need all the api Devise inherited controllers need to pass through ApiBaseController for api_authentication() check and ActiveAdmin Devise controllers do not need to pass through ApiBaseController.

Thanks in advance.

Service worker is not registering on chrome

I know service worker and push notification wont work without https SSL certificate so in my rails 3 app on dev environment i have setup self signed certificate for dev environment so all urls are opening with https. So now this service worker thing works on mozilla browser but its giving me following error on chrome Service Worker error :^( DOMException: Failed to register a ServiceWorker: An SSL certificate error occurred when fetching the script. Please help me with this.

lundi 30 mai 2016

How can i map one query result to another query result in ruby on rails

Hi I am new to ruby on rails development. I have two queries with different model. My first_query is get from question model and second query is get from favourite model. I want to map with a column user_favourite from second query result to first query result.

this is my controller queries

def index
    @first_query = Question.order('created_at DESC').page(params[:page]).per( (ENV['ILM_QUESTIONS_PER_PAGE'] || 5).to_i )
    @second_query=Favourite.with_user_favourite(@user)
    @combined_queries = @first_query + @second_query
end

favourite.rb

scope :with_user_favourite, -> (user) {
    joins(:user).
    where(favourites: {user_id: user})
  }

index.json.builder

json.questions @combined_events

json for the result is

{
questions: [      #this is first query result
        {
            id: 88,
            user_id: 28,
            content: "test32",
            image: {
            url: null,
            thumb: {
                url: null
            },
            mobile: {
                url: null
            }
            }
        },
        {
            id: 87,
            user_id: 18,
            content: "testing riyas",
            image: {
            url: null,
            thumb: {
                url: null
            },
            mobile: {
                url: null
            }
            }
        },
        {              #this is second query result
            id: 1,
            user_id: 2,
            question_id: 84,
            created_at: "2016-05-12T06:51:54.555-04:00",
            updated_at: "2016-05-12T06:51:54.555-04:00"
        },
        {
            id: 2,
            user_id: 2,
            question_id: 81,
            created_at: "2016-05-12T07:23:47.770-04:00",
            updated_at: "2016-05-12T07:23:47.770-04:00"
        }
    ]
}

i want response like

{
questions: [      
        {                            #first query result
            id: 88, 
            user_id: 28,
            content: "test32",
            image: {
            url: null,
            thumb: {
                url: null
            },
            mobile: {
                url: null
            }
            },
            user_favorite: {       #corresponding result from second query result
                id: 1,
                user_id: 2,
                question_id: 88
            }
        },
        {                           #first query result
            id: 87,
            user_id: 18,
            content: "testing riyas",
            image: {
            url: null,
            thumb: {
                url: null
            },
            mobile: {
                url: null
            }
            },
            user_favorite: {}       #corresponding result from second query result if there is no result for particular question in favourite table
        },
    ]
}

Please Advice me on this issue

Thanks in Advance.

includes called on a relation in AR. Does it scope on the relation or the entire database?

I have an odd situation where an has_many association yields me an empty collection but a scope on an empty collection yields me a record. Any idea what is going on?

class Person
  has_many :apples

end

Class Apple
  belongs_to :person

  scope :rotten, -> { includes(pit: :seed).where(seeds: { seed_type_id: Seedtype.edible.id})
end

Inside the Person model:

=> Apple.all
[
    [0] #<Apple:0x007fdff8b49b70> {
                           :id => 1,
                      :user_id => 1,
    }
]

=> apples
[]

=> apples.rotten
[
    [0] #<Apple:0x007fdff8b49b70> {
                           :id => 1,
                      :user_id => 1
    }
]

Any ideas as to what is going on?

create array with elements form different arrays and different index for each one Ruby

How can i create 3 new arrays with elements form different arrays and different index for each one?

a = [1,2,3]
b = [:blue, :red, :yellow]
c = ["Tacos", "Burritos", "Chilli"]



new_array1 = [1,:yellow,"Tacos"]
new_array2 = [2,:rojo,"Burritos"]
new_array3 = [3,:blue,"Chilli"]

Rails not assigning proper ids

I have a program with service_provider and service models. The service_provider uses the has_many attribution and the service model uses belongs_to attribution. service_provider was created using devise. I am unable to assign a service_provider_id to the service in the create method.

The create method in services_controller.rb

def create
    @service = Service.new(service_params)
    @service.service_provider_id = current_service_provider.id    
    respond_to do |format|
      if @service.save
          format.html { redirect_to @service, notice: 'Service was     successfully created.' }
          format.json { render :show, status: :created, location: @service }
      else
          format.html { render :new }
          format.json { render json: @service.errors, status: :unprocessable_entity }
      end
    end
end

The rails console gives service_provider_id: nil for every service.

Here's the schema.rb where service_provider_id was created using the migration "t.belongs_to :service_provider, index: true"

create_table "service_providers", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
end

add_index "service_providers", ["email"], name:   "index_service_providers_on_email", unique: true
add_index "service_providers", ["reset_password_token"], name:  "index_service_providers_on_reset_password_token", unique: true
create_table "services", force: :cascade do |t|
    t.integer  "service_provider_id"
    t.string   "service_name"
    t.text     "description"
    t.integer  "price"
    t.string   "location"
    t.datetime "created_at",          null: false
    t.datetime "updated_at",          null: false
end

add_index "services", ["service_provider_id"], name: "index_services_on_service_provider_id"

Here's the service.rb model

class Service < ActiveRecord::Base
   attr_accessor :service_provider_id
   belongs_to :service_provider
   validates_presence_of :description, :location, :service_name, :price
end

And the 'service_provider.rb`

class ServiceProvider < ActiveRecord::Base
  has_many :services
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
end

I tried restarting the server and resetting the database with no luck.

How to run migration generation from console?

I want to try to generate migration inside rails console.

This file is responsible for migration creation (particularly create_migrate_file method):

rails/generators/active_record/migration/migration_generator.rb

enter image description here

But, for some reason, in my console I can't call ActiveRecord::Generators::MigrationGenerator class.

enter image description here

NameError: uninitialized constant ActiveRecord::Generators::MigrationGenerator

What can I do in this case?

Ruby on Rails Multiple Select

I have a three tables Plan, Channel and ChannelCategory. While creating a new Plan I want to select multiple channel_categories and based on that I want to select multiple channels. Please provide me the solution.

Subcategories & Categories in Rails

I have the following setup to handle categories and sub categories.

Category.rb

class Category < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, use: :slugged

  has_many :subcategories
  has_many :products ,:through => :subcategories
end

Subcategory.rb

class Subcategory < ActiveRecord::Base
  belongs_to :category
  has_many :products
end

Product.rb

class Product < ActiveRecord::Base
  acts_as_taggable
  extend FriendlyId
  friendly_id :name, use: :slugged
  belongs_to :subcategory
end

Do I need to add a category_id:integer & subcategory_id:integer to the products model make it work, or does Rails handle this for me automatically?

Is there any method in Rails that creates basic structure for migration?

For example I have the following code:

create_table "users", force: :cascade do |t|
  t.string  "name"
end

Instead of appending strings myself, I'd like to call some method that would build basic migration skeleton for it like this:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table "users", force: :cascade do |t|
      t.string  "name"
    end
  end
end

How to compare Hour and minute in Ruby for Time datatype

I am writing code to determine when to show site announcement for our site. Admin are allowed to set start_time and finish_time to display site announcement. Announcement should only be displayed between those times. Admin can select different time for weekdays and different time for weekends.

The way I am checking now is something like this:

time = Time.now
current_hour = time.strftime('%I').to_i
current_minute = time.min

announcement_start_hour = start_time.strftime('%I').to_i
announcement_start_minute = start_time.min

announcement_finish_hour = finish_time.strtfime('%I').to_i
announcement_finish_minute = finish_time.min

then i have logic something like this

if (current_hour >= announcement_start_hour && current_hour <= announcement_finish_hour) &&(announcement_start_minute >= current_minute && current_minute < announcement_finish_minute)

  // show announcement

else

  // don't show announcement

But the problem that I am encountering is let's say our current time is 1 pm and our announcement is supposed to be displayed form 11 am until 11 pm

So,

curernt_hour = 1
current_mintue = 00

announcement_start_hour = 11
announcement_start_minute = 00

announcement_finish_hour = 11
announcemnt_finish_minute = 00

so current_hour >= announcement_start_hour will be false because ( 1 is < 11) but in reality 1 is 1 pm which is 13 in 24 hr time.

There needs be better way to compare hour and minutes for Time in Ruby. I will encounter similar problem even when i use 24 hr format for time.

NOTE: data type for both start_time and finish_time is Time not DateTime

confusion in ruby on rails

I'm new in ruby on rails.Encountered a line

<span id="searchTab" class="<%=yield(:search_tab_id)%>"><%=link_to "Search", search_items_path %></span>

what the line is doing exactly.

I want to implement another tab here named "XYZ" what are the steps I should follow.

what all things I have to add in controllers,views,routes etc

Rails aways renders the application.html.erb instead of wanted views

My Ruby on Rails application always renders the layouts/application.html.erb view instead the views I want it to. Has anyone an Idea why that might be so? My routes file looks like this:

   Rails.application.routes.draw do
     root 'startup#index'
     resources :users
   end

And my application_cotroller.rb is pretty much empty:

   class ApplicationController < ActionController::Base
      protect_from_forgery with: :exception
   end

dimanche 29 mai 2016

Delay evaluation of .js.erb to server while precompiling assets on development machine

I have an app which uses an API key for a particular API. The API has both test and live keys, and I want the key to be configurable. I'm using the key in a .js file, so I made it into a .js.erb file and added <%= ENV[API_KEY] %> to set it from the environment variable (which is set appropriately for test or live). However, since I pre-compile the assets on my development machine, I'm getting the test key in production, even though I've got the live key defined on the production machine. I don't see a way around this issue. Is there a different best practice for accomplishing this?

ruby on rails web service not working after upgrade to rails 4.x

some time ago, i've written a web application using RoR v.3.2.13... all was tested and working correctly for some time... now, i'm going to update all the environment to rails 4.2.5! i've found a lot of issues upgrading the framework, all was solved almost easily finding a lot of suggestions on the web!!

the last one is giving me some more troubles...

well, i've the needing to upload an .xml stream from a palm device to the server to update some database records....

this is an example of the .xml stream the mobile terminal is sending to the server:

<?xml version="1.0" encoding="utf-8"?>
<readings>
 <reading>
  <opercode>a001a</opercode>
  <barcode>000073680</barcode>
  <opid>4</opid>
  <datetime>2012-01-22T00:07:34+01:00</datetime>
 </reading>
 <reading>
  <opercode>a001a</opercode>
  <barcode>000073679</barcode>
  <opid>4</opid>
  <datetime>2012-01-22T00:07:38+01:00</datetime>
 </reading>
</readings>

as you can see, it contains a bounch of readings containing four fields each.

in case the wireless connection is not working, i've built a view that contains an html form and a file upload field....

the controller receives the stream using the same action as you can see here:

.........................
#
# receives the readings stream and passes it to the parser
def upload
  #
  # different part of code if request is from .html o .xml
  respond_to do |format|
    # the request is from .html page
    format.html do
      # checks the uploaded file 'content type'
      if params[:readings_file].instance_variable_get(:@content_type) == "text/xml"
        # the file is .xml
        # identifies the readings operator_id
        operator_id = Operator.find_by_code(params[:readings_file].instance_variable_get(:@original_filename)[0..4]).id
        # retrieves the number of readings stored into .xml file
        original_filename = params[:readings_file].instance_variable_get(:@original_filename).partition(".")[0]
        expected_readings = original_filename.partition("-P-")[2].to_i != 0 ? original_filename.partition("-P-")[2].to_i : original_filename.partition("--")[2].to_i
        # binds the temporary file for nokogiri parsing
        temp_file = File.open(params[:readings_file].instance_variable_get(:@tempfile))
        readings_to_be_loaded = Nokogiri::XML(temp_file)
        # parses the readings records
        result = parse_xml(readings_to_be_loaded, operator_id)
        # checks parsing result against expected readings count
        if result != expected_readings
          message = "WARNING - Inside .xml " + expected_readings.to_s + " records was present, only " + result.to_s + " has been accepted as valid readings!!"
        else
          message = "OK - .xml stream succesfully parsed!"
        end
      else
        # the file is not .xml
        message = "ERROR - Invalid readings file format detected --> 'not xml'!!"
      end
      logger.debug message
      redirect_to readings_path, :flash => {:message => message} and return
    end
    #
    # the request is from .xml stream
    format.xml  do
      if params[:readings].present?
        # determines the number of expected readings inside the stream and retrieves the operator code
        if params[:readings][:reading][0].nil?
          expected_readings = 1
          oper_code = params[:readings][:reading][:opercode]
        else
          expected_readings = params[:readings][:reading].count
          oper_code = params[:readings][:reading][0][:opercode]
        end
        # initializes the good readings counter
        readings_count = 0
        ........

        omissis

        ........
      else
        # the stream don't contains readings, return the http error code 406 -> 'Not Acceptable'
        logger.debug "ERROR - Readings file content is incorrectly formatted!!"
        render nothing: true, status: 406 and return
      end
    end
  end
  # not .xml request nor html upload
  # nothing has been processed, ingores the upload and returns status code 404 -> 'resource not found'
  logger.debug "ERROR - Incorrect data stream content"
  render :nothing => true, status: 404 and return
end
................

then differentiate action if the data stream was uploaded from html as file or directly as .xml stream.

now, if i upload the file using the html view, all works fine (both rails 3.2 or 4.2 are correctly working and parsing readings)....

to simulate the direct .xml upload action using console on terminal, i use this command line:

curl -v -H "Content-Type: application/xml; charset=utf-8" --data-ascii @a001a-12115-81843-P-5.xml http://localhost:3000/readings/upload.xml

if the stream is uploaded directly using .xml format... rails 3.2 runs fine, rails 4.2 returns "406 Not acceptable" (see extracted logs row!)

log from rails 3.2:

Started POST "/readings/upload.xml" for 127.0.0.1 at 2015-01-22 21:32:35 +0100
Processing by ReadingsController#upload as XML
  Parameters: {"readings"=>{"reading"=>[{"opercode"=>"a001a", "barcode"=>"000073685", "opid"=>"4", "datetime"=>"2015-01-21T20:18:20+01:00"}, {"opercode"=>"a001a", "barcode"=>"000073683", "opid"=>"4", "datetime"=>"2015-01-21T20:18:24+01:00"}, {"opercode"=>"a001a", "barcode"=>"000073682", "opid"=>"4", "datetime"=>"2015-01-21T20:18:28+01:00"}, {"opercode"=>"a001a", "barcode"=>"000073679", "opid"=>"4", "datetime"=>"2015-01-21T20:18:36+01:00"}, {"opercode"=>"a001a", "barcode"=>"000073683", "opid"=>"4", "datetime"=>"2015-01-21T20:18:41+01:00"}]}}
  Rendered text template (0.0ms)
Completed 200 OK in 49ms (Views: 48.2ms | ActiveRecord: 0.0ms)

log from rails 4.2:

Started POST "/readings/upload.xml" for 127.0.0.1 at 2016-05-27 21:11:38 +0200
Processing by ReadingsController#upload as XML
ERROR - Readings file content is incorrectly formatted!!
  Rendered text template (0.0ms)
Completed 406 Not Acceptable in 2ms (Views: 0.2ms | ActiveRecord: 0.0ms)

it seems like parameters are not reaching the controller action at all!! (i suppose this is due to some kind of restriction on 4.2 version of framework but i'm unable to find any specific info confirming or disproving my suspects)

PLS NOTE: if i try to send the stream directly using the palm device, i receive the same response!!

any suggestion is well accepted,

many thanks in advance to you all... Francesco

Rails API Does not split Json

Weird problem. If the class at the bottom was a module, split the Json without problems, if it was only methods, also works, but the problem is.. when it is a class, it does nos split the Json anymore, returns an empty array.. however, if being a class I do a puts in the class to check the object, it actually puts the object.. Any thoughts about why? How can I fix it?

I have this controller:

 def index
   begin
     call_employee_work_locations_api
      rescue => ex
      render :json => {"service unavailable": "0001" }, :status => :service_unavailable
   end 
 end

I have this service:

def call_employee_work_locations_api
   auth = {:username=>ENV["USERNAME"], :password=>ENV["PASSWORD"]}
   employee_locations = HTTParty.get(employee_work_Location_url , :basic_auth => auth)
   #serialize_work_location(employee_locations) 
   serializer = EmployeeSerializer.new
   serializer.serialize_work_location(employee_locations)
end 

I have this builder:

json.array!(@top_locations) do |location|
   json.extract! location, :name, :description, :latitude, :longitude
end

I have this class:

class EmployeeSerializer

    def serialize_work_location(employee_locations)
        employee_locations= JSON.parse(employee_locations)
        locations=[]

        employee_locations["work_locations"].each do |attributes|
           location = Location.new(attributes["latitude"],attributes["longitude"],attributes["description"],attributes["name"])
          locations.push(location)
        end
        employee_locations_selector(locations)
    end 

    def top_office_location_selector(locations, city)
        top_locations=[]
        locations.each do |office|
            if office.name == city[0] then top_locations.push(office) end
            if office.name == city[1] then top_locations.push(office) end
        end
        @top_locations = top_locations
        p @top_locations <--- it prints the object perfectly, but does not pass to the view, I get an empty array instead.
     end

     def employee_locations_selector(locations)
        city = locations.each_with_object(Hash.new(0)) { |locations, counts| counts[locations.name] += 1 }.max_by{|k,v| v}
        top_office_location_selector(locations, city)
     end
end

Rails 'rapidfire' gem, is it possible to set a one chance limit per user for taking the survey/exam?

I´m trying to do this, but I can´t find out how to:(

I´m creating a simple teachers/students plataform (a teacher creates exams online, a student take the exam(s)).

Everything seems to work with the gem, but the main porpose isn´t working, a student is not supposed to be able to answer a test several times. I´m not a rails expert of course, but I´d like if you´d guide me in the right direction.

My rapidfire questions_groups/index.html.erb has something like these(I think this is the important part)

<%= render partial: "question_group", collection: @question_groups%>

And my _questions_group.html.erb partial has this:

<tr id= "question_group_<%= question_group.id %>">
  <td>
    <% if can_administer? %>
      <%= link_to question_group.name, question_group_questions_path(question_group) %>
     <% else %>
      <%= question_group.name %>
    <% end %>
   </td>
<td>
  <ul class="horizontal-list">

  <!--######### My problem!!!!-->
  <% @answer_groups.each do |answer_group| %>
    <%if current_user.id!=answer_group.user_id&&answer_group.question_group_id!=question_group.id%>
       <li><%= link_to "Answer Questions", new_question_group_answer_group_path(question_group) %></li>
    <%end%>        
  <%end%>
  <!--#########-->

  <% if can_administer? %>
    <li><%= link_to "Results", [:results, question_group] %></li>
    <li><%= link_to "Delete", [question_group], method: :delete %></li>
  <% end %>
  </ul>
 </td>
</tr>

I thought about a solution, and iterated through that @answer_groups collection in order to know if the user has answered the question_group before, BUT I couldn't because I needed to define the collection, but I wasn´t able to properly pass it together with the @question_groups that is passed when the partial is rendered in the index.

I'd like some help please. Thank you!

samedi 28 mai 2016

Ruby on Rails, Enum user conditions from a different table

I have enums declared as follows in a table separate from my main users table (User.rb). I sign up users and give them a role from this table:

school_user.rb

class SchoolUser < ActiveRecord::Base
    belongs_to :user
    belongs_to :school

    enum user_type: [:school, :student, :parent, :teacher]

def school?
end

def teacher?
end

def student?
end

def parent?
end


end

I don't think I have to define each role here but I tried it.

I was using a boolean method to separate the users before but switched to enum. I used to use this method type to restrict views based on role:

...unless current_user.teacher?...

This worked fine but now I have the enums declared in a different model to the users table it does not work.

A user has a role through the relationship between user.rb and school_user.rb. This works. I'm just looking for a way to set access based on user role/type in the views as above.

I hope not but I presume I will have to change all the conditions throughout my application?

I tried:

...unless current_user.school_user.teacher?...

and other variations.

Would appreciate any help. Thanks.

how to make Javascript alert box display a variable from Rails controller

I have this piece of Javascript codes in my view file:

<script>
function hint() {
    var str = @user.name;
    var name = str.toLowerCase();

    alert(name);
}
</script>

I want the alert box to display the name of the user so I use the variable @user that was defined in my controller. However, when I click the button to active the alert box, nothing shows up. I also tried current_user.name, but it didn't work either. How can I display the value of a variable in the alert box?

Best use of content_tag in a custom link_to helper method

What is the best way to use a custom helper method in order to generate html tags with links and html options?

lets say

def drop_document_options(title,document,version,html_options)


end

in order to generate a link with the parameters:

<div class="dropdown">
<button class="btn btn-default btn-sm dropdown-toggle" type="button" data-toggle="dropdown">

<%=@hebrew_document[document]%>  - <%=@hebrew_version[version]%>

<span class="caret"></span></button>

<ul class="dropdown-menu dropdown-menu-right">

  <li> <%=link_to( {:controller => "invoices",
                      :action => "download",
                      :id => document.id,
                      :disposition => 'inline',
                      :version => version[i]} ,
                      html_options )  do %>

                      <%=action_title%>
    <% end %>

   </li>
  </ul>
</div>

vendredi 27 mai 2016

after_update callback not acting as expected in Rails 3.2

I can't seem to get my callback to function as expected.

after_update :erase_reset_token, :on => :update, :if => :password

This calls a method on the User's model that should erase the password reset token from the database, but should only fire if it is the password that has been touched.

It's gotta be the syntax, but I can't figure it out. Any help, please?

Add module to Test Class

To a test class, Im trying to add a module:

require "test_helper"
require "before_find_helper"

class User::FindOrCreateTest < ActiveSupport::TestCase
  include BeforeFindHelper

the module looks like this one:

module BeforeFindHelper
  extend ActiveSupport::Concern

  self.before do
    class FakeController < ApplicationController
     ......
    end
  end
end

Basically before the before-block was defined in the controller and everything worked fine:

  before do
    class FakeController < ApplicationController
     ......
    end
  end

But now with the included module I get this error when running the Test:

undefined method `before' for BeforeFindHelper:Module

How can I get the tests working again? Thanks

Controller in helper_method not showing views Ruby on Rails

I'm new in Ruby on Rails and web programming. I have this code view new.html.erb

<h1>EVALUATING MODEL PERFORMANCE</h1>
<%= test %>
<%= "#{controller_name}/#{action_name}" %>

and the controller articles_controller.rb

class ArticlesController < ApplicationController
    def new
    y = R.pull "capture.output(summary(rnorm(10)))"
    puts y
    end

    helper_method :test
    def test
    sample_size = 10
    R.eval "x <- rnorm(#{sample_size})"
    R.eval "summary(x)"
    R.eval "sd(x)"
    y = R.pull "capture.output(summary(rnorm(10)))"
    puts y
    end
end

And the Output ruby in web not showing def test... why ?

and why i use rinruby ?, because my professor order me. i don't want to, but and order is just and order.

just there is no error... but not showing...

Rails using helper method in form_tag select_tag

I have a view in my Rails app where I'm wanting to select a unit to dispatch to a call. Here is what it currently looks like.

   <%= form_tag dispatch_call_call_path(call), :class => "dispatch-form-tag" do  %>
   <%= select_tag(:unit_ids, options_from_collection_for_select(Unit.active.order("unit_name ASC"), "id", "unit_name"), :include_blank => true, :required => true, :class => 'select' )%>
   <%= button_tag 'Dispatch', class: 'btn btn-danger btn-small', data: {disable_with: "<i class='icon-spinner'></i>Processing..."} %>
   <% end %>

This works fine and dandy but I want to display more information about the unit in the dropdown such as whether or not they are on a call and their status.

I wrote this helper under calls_helper

def unit_select
   Unit.active.order("unit_name").map{|unit| unit.calls.where(call_status: "open").empty? ? ["#{unit.unit_name} #{unit.unit_type.unit_type}", unit.id] : ["#{unit.unit_name} (on call) #{unit.unit_type.unit_type}", unit.id] }
 end

Which when used in a form gives me Unit name (on call) Unit type if the unit is on a call.

When I am creating a new call from scratch this is how I use it in the form.

      <%= f.select(:unit_ids, unit_select,  {}, {:multiple => true, :class => 'select'}) %>

I want to use this same helper in my index view so when a unit is dispatched to a call the user sees the same information that they would when they are creating a call.

But I'm not sure how to use my unit_select helper in a select_tag. I've read the API docs for Rails but can't seem to figure this one out.

Any help is greatly appreciated.

jeudi 26 mai 2016

Filtering models with pagination only filters first page - rails 3

I have a model which I am filtering based on some parameters given by the user. The filtering works just fine but once I start using pagination, only the records from the first page are filtered and the others are ignored. This is my code in the controller for filtering:

 @start_date = params[:start_date]
 @registers = Register.all.order("payment_date DESC").page(params[:page]).per(params[:all] ? nil : Kaminari.config.default_per_page)
 @registers.delete_if { |r| !(r.payment_date <= @end_date && r.payment_date >= @start_date) if (@start_date.present? && @end_date.present?) }

And in the view I use <%= paginate @registers %> to paginate the list.

Devise with Rails Not Creating Users Properly

I'm a Rails beginner, and I am trying to make a site with a signup page that creates users in a database I set up. I installed devise (seemingly) correctly, and after creating the first user to test it out, everything seemed to work. However, if I try creating another user, it doesn't work. After clicking create user on the page, it goes back to the homepage without any errors or anything. But when I check the users table in my database, I can see the user was not created.

I got it to work when I changed the first users id (primary key) from 2 to 1. And the new user's id was 3. So it looks like for whatever reason, devise wants to skip a step, or is somehow trying to insert twice or something. But once again, even after I got the new user to create, if I try again it doesn't work.

Here's a printout of the rails server during the create request:

Started POST "/users" for ::1 at 2016-05-26 16:08:26 -0400
Processing by RegistrationsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"zl39rAOLLSRoEZUIcX574BlJtNgySlz/d5FRNIg3ZjuvcdQJxOVLDdWPAp3jQqhT3g1H0PCexFdHdmAQD81CKQ==", "user"=>{"first_name"=>"asdasd", "last_name"=>"asdasd", "email"=>"asdasd@asda.com", "password"=>"[FILTERED]", "confirm_password"=>"[FILTERED]"}, "instructor"=>"1", "commit"=>"Create my account"}
  User Load (0.5ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 4  ORDER BY `users`.`id` ASC LIMIT 1
Redirected to http://localhost:3000/
Filter chain halted as :require_no_authentication rendered or redirected
Completed 302 Found in 39ms (ActiveRecord: 0.5ms)

Here is my UsersController file:

class UsersController < ApplicationController

  def index
    @users = User.all
  end

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

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

  def new
    @user = User.new
    @user.active = 1
  end

   def create
     @user = User.new(sign_up_params)    # Not the final implementation!
     if @user.save
       redirect_to :action => :index
     else
       render 'signup'
     end
   end

  def destroy
    @user = User.find(params[:id]).destroy
    if @user.destroy
      redirect_to users_path
    else
      render 'index'
    end
  end

 private

   def user_params
     params.require(:user).permit(:first_name, :last_name, :email, :instructor, :active)
   end

end

And here is my new.html.erb file:

<h1>New User</h1>

<%= render 'form' %>

<%= link_to 'Back', users_path %>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@user) do |f| %>
      <%= f.label :first_name %>
      <%= f.text_field :first_name %>

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

      <%= f.label :email %>
      <%= f.email_field :email %>

      <%= check_box_tag(:instructor) %>
        <center><%= label_tag(:instructor, "I want to be an instructor") %></center>
      <br>
      <br>
      <%= f.label :password %>
      <%= f.password_field :password %>

      <%= f.label :confirm_password %>
      <%= f.password_field :confirm_password %>

      <%= f.submit "Create my account", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>

Thanks for any help that you can provide

Rails check_box_tag keep checked state (if checked) after page load

I'm following this guide for multi-checkbox in rails. I am using Rails 3 conventions, so I still have attr_accessible instead of strong parameters. Everything seems to work fine except I get this error:

undefined method `match' for []:Array

userprofile.rb model:

class Userprofile < ActiveRecord::Base

  before_save do
    self.expertise.gsub!(/[\[\]\"]/, "") if attribute_present?("interest")
  end

  attr_accessible :interest, :user_id, :country, :state_prov, :city
  serialize :interest, Array

userprofiles_helper.rb:

module UserprofilesHelper
  def checked(area)
      @userprofile.interest.nil? ? false :      @userprofile.interest.match(area)
  end
end

_form.html.erb:

<h3>Area of Interest</h3>

  <%= label_tag 'interest_physics', 'Physics' %>
  <%= check_box_tag 'userprofile[interest][]', 'Physics', checked("Physics"), id: 'interest_physics' %>

  <%= label_tag 'expertise_maths', 'Maths' %>
  <%= check_box_tag 'userprofile[interest][]', 'Maths', checked("Maths"), id: 'interest_maths' %>

If I remove the checked helper method, then the checkbox value does not persist. I've been trying to fix the undefined method 'match' error. Or find an alternate way to keep the correct checkbox value checked when I edit the form.

Any suggestions would help, thank you!

Failing to create a new record in rails

I'm attempting to create a new StockOrder by passing a JSON object from my front end to the server. The defined strong parameters for the StockOrders looks like this:

private
  def stock_order_params
    params.require(:stock_order).permit( [StockOrder.strong_params, :purchaser_id, :carriage_terms, :carriage_cost, :contact_id, :user_id, :currency, :default_vat_rate, :discount_cost, :dispatched_status, :due_date, :internal_notes, :invoice_address_id, :invoice_date, :payment_terms, :po_date, :vat_rate, :purchase_order_number, {stock_order_line_items_attributes: [StockOrderLineItem.strong_params, :_destroy, :id, :part_id, :description, :quantity, :unit_cost, :vat_rate, :quantity_to_dispatch, :sort_index] + StockOrderLineItem.additional_params}, :purchaser_notes, :delivery_address] + StockOrder.additional_params )
  end

In this you can see that I have two models: StockOrder & StockOrderLineItem.

Here is what I'm sending from my front-end:

{
 "stock_order":
    {
     "stock_order_line_items_attributes":
        {
         "part_id":2309,"unit_cost":15,
         "quantity_to_dispatch":5
        },
     "contact_id":10,
     "purchaser_id":10
    }
 }

And finally here is how I'm trying to create my new StockOrder:

@stock_order = StockOrder.new(stock_order_params)

But the server responds with this error:

Rails controller error

But I've looked at the models for both and, of the parameters that I'm passing, none of them are strings. Here's a snapshot of the schema for the tables:

# == Schema Information
#
# Table name: stock_orders
#
#  id                        :integer          not null, primary key
#  ref_no                    :integer
#  purchase_order_number     :string
#  contact_id                :integer
#  purchase_order_date       :date
#  carriage_terms            :text
#  payment_terms             :text
#  due_date                  :date
#  purchaser_id              :integer

And for the StockOrderItemList

# == Schema Information
#
# Table name: stock_order_line_items
#
#  id                     :integer          not null, primary key
#  stock_order_id         :integer
#  part_id                :integer
#  quantity               :decimal(, )
#  vat_rate               :float
#  unit_cost_cents        :integer
#  net_cost_cents         :integer
#  total_cost_cents       :integer
#  vat_cost_cents         :integer
#  local_unit_cost_cents  :integer
#  local_net_cost_cents   :integer
#  local_total_cost_cents :integer
#  local_vat_cost_cents   :integer
#  quantity_dispatched    :decimal(, )
#  created_at             :datetime         not null
#  updated_at             :datetime         not null
#  description            :text
#

has_many through with includes

This are the two models which i am using to query this

model 1
 has_many :locks_order_items, dependent: :destroy
 has_many :locks, through: :locks_order_items

model 2
 belongs_to :order_item
 belongs_to :lock

Form

<%= f.fields_for :order_items, @order_items do |f1| %>
   <% f1.object.locks_order_items.order("locks_order_items.check
   DESC, locks_order_items.id ASC").each do |m| 

   end %>
<% end %>

This is the query running, when load the form

SELECT "locks_order_items".* FROM "locks_order_items" WHERE 
"locks_order_items"."order_item_id" = 4444 ORDER BY 
locks_order_items.check DESC, locks_order_items.id ASC

if we have 10 entries in model 2, this above query, will run 10 times, i have tried to add includes, but still its running like that, is there any way to run that in one query with includes

Net::SMTPAuthenticationError: 435 4.7.8 authentication failed

Server just randomly crashing with with this error.

An error occurred when sending a notification using 'email' notifier. Net::SMTPAuthenticationError: 435 4.7.8 Error: authentication failed: UGFzc3dvcmQ6

What is that supposed to mean? This is a project written by not me, so I am a little confused.

As I know, UGFzc3dvcmQ6 means "password". To I need to configure ActionMailer password then?

In ruby on rails 3,how to implement a login functionality without a database?

I want to create a login page for my project and validate a user without using any database.How can i do this? Is it possible with cache? Please guide me.

Rails 3 Streaming Video or Rails HTTP Streaming

I recently implemented JP video player or J Player in my Rails 3 app to stream video tutorials, but issue is video is not streamed in chunks means if size of video is 100MB then after that 100MB gets downloaded on browser then only video will play. To overcome this issue i have implemented http streaming using this rails cast http://ift.tt/lL3ZLw Even then the video is getting fully downloaded. I am not able to understand what wrong i have done. When i am using curl -i command it shows me Transfer-Encoding: chunked but it is not working as youtube or other video sites work.

Rails- paperclip- NoMethodError

I'm trying to make a movie review app in rails. This includes adding movie image and text fields. I'm using the paperclip gem for image upload. I am getting this error while adding movie.

NoMethodError in Movies#create

Showing - MovieReview/app/views/movies/_form.html.erb where line #2 raised:

undefined method `map' for nil:NilClass
Trace of template inclusion: app/views/movies/new.html.erb

Rails.root: /Review/MovieReview

I am rendering a form partial in my movies/new,html.erb. Following is code snippet from movies/_form.html.erb

<%= simple_form_for @movie, :html => { :multipart => true} do |f| %>
   <%= select_tag(:category_id, options_for_select(@categories), :prompt => "Select a Category") %>

  <%= f.file_field :movie_img %>
  <%= f.input :title, label: "Movie Title" %>
  <%= f.input :description %>
  <%= f.input :director %>
  <%= f.button :submit %>

Movies Controller

class MoviesController < ApplicationController
  def new
        @movie = current_user.movies.build
        @categories = Category.all.map{ |c| [c.name, c.id] }
    end

    def create
        @movie = current_user.movies.build(movie_params)
        @movie.category_id = params[:category_id]

        if @movie.save
            redirect_to root_path
        else
            render 'new'
        end
    end

PS: I have added image parameter in the movie_params method which is their in the private section- Following is the code snippet

def movie_params
        params.require(:movie).permit(:title, :description, :director, :category_id, :movie_img)
    end

Movies Model

class Movie < ActiveRecord::Base
    belongs_to :user
    belongs_to :category

  has_attached_file :movie_img, styles: { movie_index: "250x350>", movie_show: "325x475>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :movie_img, content_type: /\Aimage\/.*\Z/
end

Rails 3 best_in_place_if how to show confirm alert box before the action gets completed

I am using best_in_place_if for inline editing. Here a column value gets changed just by clicking on the value. Suppose column is status and values are 'yes' and 'no'. So its like a toggle effect. If user clicks on this column, then a call goes to server and it fires a query to toggle the value in database.

I want to show a alert box showing a confirmation message, like we do for delete. If user clicks on yes then fine otherwise do not complete the call.

best_in_place_if(current_user.admin,trip,:is_active, :type => :checkbox, :classes => 'trip_disable')

mercredi 25 mai 2016

rails s not working when I enter it on terminal

when I try to input rails s on my terminal this is what i get

=> Booting WEBrick
=> Rails 4.2.6 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[Simple Form] Simple Form is not configured in the application and will use the default values. Use `rails generate simple_form:install` to generate the Simple Form configuration.
Exiting
/Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load': /Users/julian/Desktop/forum/config/routes.rb:12: syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError)
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `block in load'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/application/routes_reloader.rb:40:in `block in load_paths'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/application/routes_reloader.rb:40:in `each'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/application/routes_reloader.rb:40:in `load_paths'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/application/routes_reloader.rb:16:in `reload!'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/application/routes_reloader.rb:26:in `block in updater'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/file_update_checker.rb:75:in `execute'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/application/routes_reloader.rb:27:in `updater'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/application/routes_reloader.rb:7:in `execute_if_updated'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/application/finisher.rb:69:in `block in <module:Finisher>'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/initializable.rb:30:in `instance_exec'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/initializable.rb:30:in `run'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/initializable.rb:55:in `block in run_initializers'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `each'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `call'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/initializable.rb:54:in `run_initializers'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/application.rb:352:in `initialize!'
    from /Users/julian/Desktop/forum/config/environment.rb:5:in `<top (required)>'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `block in require'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'
    from /Users/julian/Desktop/forum/config.ru:3:in `block in <main>'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `instance_eval'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `initialize'
    from /Users/julian/Desktop/forum/config.ru:in `new'
    from /Users/julian/Desktop/forum/config.ru:in `<main>'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in `eval'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in `new_from_string'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:40:in `parse_file'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/server.rb:299:in `build_app_and_options_from_config'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/server.rb:208:in `app'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/server.rb:61:in `app'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/server.rb:336:in `wrapped_app'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/server.rb:139:in `log_to_stdout'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/server.rb:78:in `start'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:80:in `block in server'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `tap'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `server'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'
    from /Users/julian/Desktop/forum/bin/rails:9:in `require'
    from /Users/julian/Desktop/forum/bin/rails:9:in `<top (required)>'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.7.1/lib/spring/client/rails.rb:28:in `load'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.7.1/lib/spring/client/rails.rb:28:in `call'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.7.1/lib/spring/client/command.rb:7:in `call'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.7.1/lib/spring/client.rb:30:in `run'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.7.1/bin/spring:49:in `<top (required)>'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.7.1/lib/spring/binstub.rb:11:in `load'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.7.1/lib/spring/binstub.rb:11:in `<top (required)>'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /Users/julian/.rbenv/versions/2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /Users/julian/Desktop/forum/bin/spring:13:in `<top (required)>'
    from bin/rails:3:in `load'
    from bin/rails:3:in `<main>'
Julians-MacBook:forum julian$ 

How can I fix this.

Ruby on Rails Refer System

I want to implement OLA and UBER like referral system. I have an User Table, Account Referral Table and I am adding Gifts from backend. I do not understand how to use association. Please guide me through.

chnage params value in request.url rails 3

After using request.url i am getting following result:

http://MySite/admin/newsletter/export_subscriber?commit=Search&page=2&search_data%5Bcompany_name%5D=&search_data%5Bemail_id%5D=&search_data%5Bend_date%5D=May25%2C+2016+12%3A17+pm&search_data%5Bjob_title%5D=&search_data%5Bsite_id%5D=1&search_data%5Bstart_date%5D=May+25%2C+2015+12%3A17+pm&search_data%5Bstatus%5D=&utf8=%E2%9C%93

I want to increment params[:page] value by 1.

Help me out.

mardi 24 mai 2016

acts_as_nested_set *** ArgumentError Exception: Unknown key: :order

Upgrading rails3.2.21 to 4.1.9 and in a class i have use acts_as_nested_set and there is a has_many relation between two class - see below code

class Area < ActiveRecord::Base
    acts_as_nested_set
    has_many :plans
end

class Plan < ActiveRecord::Base
     belongs_to :area
end

when i am try to calculate

p = Plan.first

p.area

through an error on terminal like-

ActionView::Template::Error (Unknown key: :order. Valid keys are: :class_name, :class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table):

how to fix it?

remove outer label of checkbox in ruby

I'm using ruby on my project . I need costume style for check boxes .

please find below code

<%= f.input :category_ids, :as => :check_boxes do %> <%= f.collection_check_boxes :category_ids, Category.order(:name), :id, :name do |b| b.label { b.check_box + b.text } end %><% end %>`

Using above code Im getting out like

<label for="property_space_amenities_space_amenities_2"><input type="checkbox" value="2" name="property[space_amenities][space_amenities][]" id="property_space_amenities_space_amenities_2">Internet connectivity</label>

form this im not able give custom style for this

i want output like below

<label class="control-label" for="user_login">Login</label> <input class="form-control" id="user_login" name="user[login]" type="text" />

Please help me in this

default value is not saved to the database

I want to add a default value to an existing column in my database, this is my attempt:

add_column :users, :gamelv1, :integer, default: 1

I added 'default: 1' and run 'rake db:migrate' but when I check the default value of the gamelv1 column is still 'nil'. The value '1' I added is not saved. Please show me how to solve this. Thanks.

dynamic output in ruby terminal during rake db:seed

I am working on a rather lengthy seed.rb file.

Since it takes the rake task a while to complete, I want to give visual feedback through the console to the user so they know the process is working.

So far, I have:

puts "Topic: #{i}, created..."

inside the create loop. However, it spams the terminal output. What I would like to do is have the output look like this:

Topic: #1..N, created...

where the output all stays on the same line, without creating a /n newline character, like what the current output looks like:

Topic: #1, created...
Topic: #2, created...
Topic: #3, created...
Topic: #N, created...

I have tried fiddling with print instead, but it just creates a long string wrapping at the end of the terminal line.

Any ideas?

EDIT This is the entire seed.rb code:

topic_list = []
i = 1
(0..9).map{
  topic_list << [ Faker::Lorem.words(rand(2..5)), Faker::Lorem.sentences(rand(3..7)), rand(1..6) ]
}
topic_list.each do |title, content, author|
  Topic.create!( title:title, content:content, author:author )
  puts "Topic: #{i}, #{title} created..."
  i += 1
end

chef-configure site in IIS

while executing the below cookbook to configure a site in IIS, I am getting the error

"cannot create a file when that file already exists" Ran C:\windows\system32\appcmd.exe start sitename:"testapp" and return 183.

where it went wrong?

search function for conversations in ruby on rails

I m new to rails. I would like to add a search function for my rails app. the user can search for the conversations that he made with other users. in that search, he can type keywords of the messages or the user name that he chatted. Can some one guide me through this...

conversation.rb is,

class Conversation < ActiveRecord::Base
belongs_to :sender, foreign_key: :sender_id, class_name: 'User'
belongs_to :recipient, foreign_key: :recipient_id, class_name: 'User'

has_many :messages, dependent: :destroy

validates_uniqueness_of :sender_id, scope: :recipient_id

scope :involving, -> (user) do
    where("conversations.sender_id = ? OR conversations.recipient_id = ?", user.id, user.id)
end

scope :between, -> (sender_id, recipient_id) do
    where("(conversations.sender_id = ? AND conversations.recipient_id = ?) OR (conversations.sender_id = ? AND conversations.recipient_id = ?)", 
                sender_id, recipient_id, recipient_id, sender_id)
end

end

message.rb is,

class Message < ActiveRecord::Base


 belongs_to :conversation
  belongs_to :user

  validates_presence_of :content, :conversation_id, :user_id

  def message_time
    created_at.strftime("%v")
  end

end

conversations_controller.rb is,

class ConversationsController < ApplicationController
before_action :authenticate_user!

def index
    @users = User.all
    @conversations = Conversation.involving(current_user)
end

def create
    if Conversation.between(params[:sender_id], params[:recipient_id]).present?
        @conversation = Conversation.between(params[:sender_id], params[:recipient_id]).first
    else
        @conversation = Conversation.create(conversation_params)
    end

    redirect_to conversation_messages_path(@conversation)
end

private

    def conversation_params
        params.permit(:sender_id, :recipient_id)
    end

end

messages_controller.rb is,

class MessagesController < ApplicationController
before_action :authenticate_user!
before_action :set_conversation

def index
    if current_user == @conversation.sender || current_user == @conversation.recipient
        @other = current_user == @conversation.sender ? @conversation.recipient : @conversation.sender
        @messages = @conversation.messages.order("created_at DESC")
    else
        redirect_to conversations_path, alert: "You don't have permission to view this."
    end
end

def create
    @message = @conversation.messages.new(message_params)
    @messages = @conversation.messages.order("created_at DESC")

    if @message.save
        respond_to do |format|
            format.js
        end
    end
end

private

    def set_conversation
        @conversation = Conversation.find(params[:conversation_id])
    end

    def message_params
        params.require(:message).permit(:content, :user_id)
    end
end

Can someone guide me to write the functionality for search and view the results of the search. i have tried in two different types but not worked. Thanks in advance

Enterprise has_many :user devise [on hold]

I have a problem, devise have implemented for users. Also I have a table called companies. It turns out that a company can have many users and need the admin can create respective users of the company in its panel. By the way, pundit use.

PD: Create an intermediate table to assign users and companies.

How to send the authenticated response while authenticating a user via SAML in Rails?

I have been trying to implement SAML in my application, wherein I want to authenticate the user and create the SAML Token(response) and redirect the user to the other website wherein session gets created. Till now I have been able to get info on init method and consume method, which will be implemented by the other website.

def init
    request = OneLogin::RubySaml::Authrequest.new
    redirect_to(request.create(saml_settings))
  end

  def consume
    response          = OneLogin::RubySaml::Response.new(params[:SAMLResponse])
    response.settings = saml_settings

    if response.is_valid? && user = current_account.users.find_by_email(response.name_id)
      authorize_success(user)
    else
      authorize_failure(user)
    end
  end

Following this Source.

I want to create the method which comes in between init and consume.

Rails Octopus Gem - Log which database queried

Does anyone have a way to check which database is being queried from ActiveRecord using Octopus Gem?

I want to check whether the read requests are actually hitting slave database and not master database.

lundi 23 mai 2016

Upgrading Rails 3 to Rails 4 rake tasks "Don't know how to build task"

I'm upgrading a Rails 3 application to Rails 4 and had existing plugins using the old vendor/plugins directory. Where possible I have switched to gems, in other cases I have moved these to lib and created initializers in config/initializers.

Some of these plugins add rake tasks that now are failing with the error "Don't know how to build task 'X' where X is any task that was migrated to the lib directory. Is there some other steps that need to be taken to migrate rake tasks when upgrading to Rails 4?

How to access hash value using a variable in ruby?

I am wondering,Is their any way i can access hash value using a variable. Example:

nested_array = ["temp"]["temp1"]
temp_hash = {"temp"=>{"temp1"=>54}}

Here i want to access 54.I know it can be accessed like x["temp"]["temp1"].But,I want to access it using variable nested_array over temp_hash hash.

How to write the below SQL query in rails 3 ActiveRecord?

select * from
(
SELECT DISTINCT ON (table1.id) table1.*, table3.date_filed as date_filed
FROM
        table1 LEFT JOIN table2 ON table2.id = table1.some_id
        INNER JOIN table3 ON table2.id = table3.some_id
WHERE
    (
        status IN('Supervisor Accepted')
    )
    AND(table3.is_main)
)first_result
ORDER BY date_filed ASC LIMIT 25 OFFSET 0

Is there any way to run main/subset query in the database side through Active::record (Rails 3). I don't want run the first_result(First db query) and the order by on the top of the result(Second db query).

I tried the below:

    # First query run   
    first_result = Table1.select('DISTINCT ON (table1.id) table1.*, table3.date_filed').
    joins('LEFT JOIN table2 ON table2.id = table1.some_id'). # I don't want a association here
    joins('INNER JOIN table3 ON table2.id = table3.some_id').
    where('table3.is_main')

    # Second query run, WHICH is UGLY and not working properly
    Table1.where(id: first_result.collect(:&id)).
    order_by('date_filed ASC')
    page(page).
    per_page(per_page)

dimanche 22 mai 2016

how to run a method multiple times in Rails controller

I'm building a game app and I want my game to move to the next level when the user got the right answer. Now my code can only move from level 1 to level 2, but from level 2, it cannot move to level 3. Here's my code:

class Game1Controller < ApplicationController

    def index
    end

    def play

        @game1 = Game1lv.find(params[:level])

        @game1l = Game1lv.where(:level => @game1).limit(1).pluck(:imagelink)
        @game1a = Game1lv.where(:level => @game1).limit(1).pluck(:answer)
        @game1link = @game1l[0].to_s
        @game1answer = @game1a[0].to_s

        @game1answer_user = params["answer"]

        if @game1answer_user == @game1answer

            redirect_to game1_play_path(@game1.level += 1), :flash => { :success => "You are right! Now try the next question" }

        end

    end

    def instruction
    end

end

I tried to use for loop inside my play method, but rails prompted the error "Render and/or redirect were called multiple times in this action.". Please show me how to solve this. Thanks.

Embed Hellosign signature in Refile PDF

I'm attempting to use the Hellosign API create an embedded signature request with a PDF that was created using pdfkit and stored/uploaded with Refile. Each contract is uniquely created for each signer, depending on the signer details.

I've followed the steps in this Ruby documentation and run into an error on the signatures_controller.rb.

# app/controllers/signatures_controller.rb

def create_embedded_request(opts = {})
    HelloSign.create_embedded_signature_request(
        test_mode: 1, #Set this to 1 for 'true'. 'false' is 0
        client_id: Settings.hellosign_client_id,
        subject: 'My first embedded signature request',
        message: 'Awesome, right?',
        signers: [
            {
               email_address: opts[:email],
               name: opts[:name]
            }
        ],
        files: ["#{Refile.attachment_url(@contract, :file, format: "pdf")}"]
    )
end

The documentation uses a gem hellosign-ruby-sdk which indicates that the filetype can be specified in these formats:

Specifying files (link here)

When using request endpoints that send files, such as a signature request, you can specify files either as

  1. A string representing the path
  2. A Ruby File Object (File.open, then assign to a variable)
  3. A Rails ActionDispatch::Http::UploadedFile

I have used the Refile attachment_url helper to generate (1) for the pdf in the code snippet above. But encountered this error:

HelloSign::Error::FileNotFound at /signatures

/attachments/e9ec551d339ed6ef62a882a30842c48dc8f25fa6/store/8d56484e3049813cc557e9f8fc628f68a0db1e76a76444890a2ddb2be54a/KL051610060 was not found on the filesystem

Am I understanding the API incorrectly? What am I doing wrong?

Thanks!!

Migrate Javascript to CoffeeScript and make it work on page load

I am attempting to have a javascript to be loaded for a field's class. Here is my view:

<%= form_for @game do |f| %>
  <div class="row">
    <div class="col-lg-4 col-md-6">
      <div class="form-group">
        <%= f.label :time %>
        <%= f.text_field :time, class: 'form-control form-datetime', readonly: true %>
      </div>
    </div>
  </div>
<%= f.submit(class: 'btn btn-success')%>
<% end %>

<script>
  $(".form-datetime").datetimepicker({format: 'yyyy-mm-dd hh:ii'})
</script>

I can only get the javascript to work on page refresh. On the first load, the page console states:

Uncaught TypeError: $(...).datetimepicker is not a function

On page reload it works fine.

I have attempted to use the document ready handler as so, with no luck:

<script>
  $( document ).ready(function() {
    (".form-datetime").datetimepicker({format: 'yyyy-mm-dd hh:ii'});
  });
</script>

I would also like to remove this <script> tag from the view and place it in the CoffeeScript file. What do I need to write in the CoffeeScript file to load this java function on first page load?

rails3 update param in controller

I want to update 2 column values in a Rails3 controller if a certain submit button is used on the form.

Submit button on form:

  <%= simple_form_for @costproject, :html => {:class => 'form-horizontal'}, :validate => true do |f| %>
...

  <%= f.submit 'Submit to Division', :class => 'btn btn-warning', :name => "submit1" %>

Update logic in Controller:

class CostprojectsController < ApplicationController
...
  def update
    ...
    params[:coststatus_id] = 2 if params[:submit1]
    params[:submit_date] = Date.today if params[:submit1]
    respond_to do |format|
      if @costproject.update_attributes(params[:costproject])
        flash[:success] = "Project Submitted"  if    @costproject.previous_changes.include?(:submit_date)
        format.html { redirect_to nextpath }
        format.json { render json: @costproject }
      else
        format.html { render action: "edit" }
        format.json { render json: @costproject.errors, status: :unprocessable_entity }
      end
    end
   end

If I stop execution with an alert, it looks like the params have been set. But, the values don't get saved to the db.

Change wildcard route based off an array from Rails 3 to Rails 4

In Rails 3, I have these:

# shop.rb
class Shop < ActiveRecord::Base
  TYPES = %w(cafe restaurant)
end

# shops_controller.rb
class SpotsController < ApplicationController
  def cafe
  end

  def restaurant
  end
end

# routes.rb
resources :shops do
  resources :reviews, :photos
  member do
    get *Shop::TYPES
  end
end

The idea is to generate get routes based off the Shop::TYPES array:

get :cafe
get :restaurant

In any case when I create another new type in Shop, I won't have to update my routes.

I am upgrading to Rails 4. What is the equivalent to get *Shop::TYPES, because I couldn't find the answer?

undefined method `_path' when using params

I'm new to Rails and currently I'm building a game app. My game contains multiple levels. I want the url of the game to contain the number of each level. For example:

http://localhost:3000/game1/play/1
http://localhost:3000/game1/play/2

In order to achieve this, I understand that I need to use params, here's my code:

routes.rb:

Rails.application.routes.draw do

  devise_for :users

  resources :game1

  get "/game1" => "game1#index"
  get "/game1/play/:level" => "game1#play"
  get "/game1/instruction" => "game1#instruction"


  get "/pages/*page" => "pages#show"
  get "/pages/about" => "pages#about"

  root "pages#show", page: "home"

end

controller:

class Game1Controller < ApplicationController

    def index
    end

    def play

        @game1 = Game1lv.find(params[:level])

        @userid = current_user.id
        @usergame1lv = User.where(id: @userid).limit(1).pluck(:game1lv) 
        if @usergame1lv == [nil]
            @usergame1lv = 1
        end

        @game1l = Game1lv.where(:level => @usergame1lv).limit(1).pluck(:imagelink)
        @game1a = Game1lv.where(:level => @usergame1lv).limit(1).pluck(:answer)
        @game1link = @game1l[0].to_s
        @game1answer = @game1a[0].to_s

        @game1answer_user = params["answer"]

        if @game1answer_user == @game1answer
            redirect_to game1_play_path(@game1), :flash => { :success => "You are right!" }
        else
            #flash.now[:alert] = 'You are wrong! Lets try again!'
        end

    end

    def instruction
    end

end

view:

<body><center>

    <br><b>Answer: </b><br><br>

    <%= form_tag game1_play_path(@game1), :method => :get, :id => "text_form" do %>

        <%= text_field_tag "answer", "" ,class: 'textbox_game' %>
        <br><br>
        <%= submit_tag("Submit", :class => "button_game") %>

    <% end %>


</center></body>

Now when I go to the url:

http://localhost:3000/game1/play/1

Rails show the error:

undefined method `game1_play_path' for #<#<Class:0x943de50>:0x9447720>

Rails indicate that the error is at this line in the view file:

<%= form_tag game1_play_path(@game1), :method => :get, :id => "text_form" do %>

Please show me what I'm doing wrong and why that method is undefined. Thanks in advance.

vendredi 20 mai 2016

How to run capistrano tasks over lossy connection?

Is it possible to run a capistrano task over a lossy connection?

E.g. if the internet drops out or your disconnect wifi, it will resume the command/task when you're back online.

I am using capistrano v3x.

Thanks,

Rails4 -undefined method `name' for nil:NilClass 4

I am getting an error message that says undefined method 'name' in my show.html.erb page. Where it says @book.category.name it keeps saying undefined method name.


show.html.erb

    <h1><%= @book.title %></h1>
<h3><%= @book.author %></h3>
<h4>Category: <%= @book.category.name %></h4>
<p><%= @book.description %></p>

<%= link_to "Back", root_path %>


<% if user_signed_in? %>
<% if @book.user_id == current_user.id %>

<%= link_to "edit", edit_book_path(@book) %>
<%= link_to "Delete", book_path(@book), method: :delete, data: {confirm: "Are you sure you want to delete book?"} %>

<% end %>
<% end %>


Books_Controller.rb

    class BooksController < ApplicationController
before_action :find_book, only: [:show, :edit, :destroy, :update]

def index
if params[:category].blank?
@books = Book.all.order("created_at DESC")
else 
    @category_id = Category.find_by(name: params[:category]).id
    @books = Book.where(:category_id => @category_id).order("created_at DESC")
end
end

def show 
end

def new
@book = current_user.books.build
@categories = Category.all.map{ |c| [c.name, c.id]}
end

 def create 
@book = current_user.books.build(book_params)
@book.category_id = params[:category_id]


if @book.save
    redirect_to root_path
else
    render 'new'
    end
end

def edit
@categories = Category.all.map{ |c| [c.name, c.id]}
end

def update
 @book.category_id = params[:category_id]
if @book.update(book_params)
    redirect_to book_path(@book)
else
    render ' new'
end
end

def destroy
    @book.destroy
    redirect_to root_path
end

 private

 def book_params
params.require(:book).permit(:title, :description, :author, :category_id, :book_img)
 end

def find_book
@book = Book.find(params[:id])
end


end


Book.rb

class Book < ActiveRecord::Base
    belongs_to :user
    belongs_to :category

    has_attached_file :book_img, :styles => { :book_index => "250x350>", :book_show => "325x475>" }, :default_url => "/images/:style/missing.png"
  validates_attachment_content_type :book_img, :content_type => /\Aimage\/.*\Z/
end


Category.rb

class Category < ActiveRecord::Base
    has_many :books
end

Rails 3 best_in_place_if how to add "id" attribute to element

I am using best_in_place_if for inline editing. Here I want to catch the id of current element edited by using the ajax success event of best_in_place.

Below is code snippet I am trying to add id attribute. But when I inspect the html, the value for id attribute is the default value generated by the bes_in_place. As per their doc, its mentioned that the default value can be changed by providing our own value.

The default value for id attribute is shown as id="best_in_place_trip_32_is_active" and I want is only id=32

best_in_place_if(current_user.admin,trip,:is_active, :type => :checkbox, :classes => 'trip_disable', :id => trip.id)

Please let me know what I am missing.

Not able to set rails environment variable in nginx passenger

I am not able to set rails env variable to production from nginx passenger config file its by default setting to development.

passenger version - 5.0.27

nginx version - 1.8.1

nginx conf file,

server {
  listen 80;
  server_name "test.com";
  passenger_enabled on;
  passenger_env_app production;
  access_log /root/NTP/log/access_log;
  error_log /root/NTP/log/error_log;
  root /root/NTP/public;
  passenger_ruby /usr/local/rvm/gems/ruby-2.0.0-p648/wrappers/ruby;
}

i get the following error,

App 26438 stderr:    /usr/lib/ruby/vendor_ruby/phusion_passenger/platform_info.rb:363: warning:   Insecure world writable dir /root/NTP/. in PATH, mode 040777
App 26438 stderr:  [passenger_native_support.so] trying to compile for the   current user (nobody) and Ruby interpreter...
App 26438 stderr:      (set PASSENGER_COMPILE_NATIVE_SUPPORT_BINARY=0 to disable)
App 26438 stderr:      Warning: compilation didn't succeed. To learn why, read this file:
App 26438 stderr:      /tmp/passenger_native_support-1o7awri.log
App 26438 stderr:  [passenger_native_support.so] finding downloads for the current Ruby interpreter...
App 26438 stderr:      (set PASSENGER_DOWNLOAD_NATIVE_SUPPORT_BINARY=0 to disable)
App 26438 stderr:      # tar xzf rubyext-ruby-2.0.0-x86_64-linux.tar.gz
App 26438 stderr:      # rm -f rubyext-ruby-2.0.0-x86_64-linux.tar.gz
App 26438 stderr:      Checking whether downloaded binary is usable...
App 26438 stderr:      # /root/.rvm/gems/ruby-2.0.0-p648/wrappers/ruby -I. test.rb
App 26438 stderr:      Binary is usable.
App 26438 stderr:      # current user is: nobody
App 26438 stderr:      # mkdir -p /nonexistent/.passenger/native_support/5.0.27/ruby-2.0.0-x86_64-linux
App 26438 stderr:      Encountered permission error, but no more directories  to try. Giving up.
App 26438 stderr:      -------------------------------
App 26438 stderr:  [passenger_native_support.so] will not be used (can't compile or download) 
App 26438 stderr:   --> Passenger will still operate normally.
App 26438 stderr: Rails Error: Unable to access log file. Please ensure that /root/NTP/log/development.log exists and is chmod 0666. The log level has been   raised to WARN and the output directed to STDERR until the problem is fixed.
App 26438 stdout: => AWS Deploy loaded!
App 26438 stdout: => Initializing CONFIG (initializers/config.rb)
App 26438 stdout: => Initializing CONSTANTS (initializers/constants.rb)
App 26438 stderr: /root/.rvm/gems/ruby-2.0.0-p648/gems/bundler-1.11.2/lib/bundler/shared_helpers.rb:78: warning: Insecure world writable dir /root/NTP/. in PATH, mode 040777
App 26438 stdout: 
[ 2016-05-20 15:30:03.3085 26405/7f1e90403700  age/Cor/App/Implementation.cpp:304 ]: Could not spawn process for application  /root/NTP: An error occurred while starting up the preloader.
  Error ID: 03accacd

And on the web page i get below error,

Web application could not be started

Error ID
    03accacd
Application root
    /root/NTP
Environment (value of RAILS_ENV, RACK_ENV, WSGI_ENV, NODE_ENV and     PASSENGER_APP_ENV)
    development
Ruby interpreter command

    /root/.rvm/gems/ruby-2.0.0-p648/wrappers/ruby

User and groups

    uid=65534(nobody) gid=65534(nogroup) groups=65534(nogroup)

Environment variables

GEM_HOME = /root/.rvm/gems/ruby-2.0.0-p648
SHELL = /usr/sbin/nologin
IRBRC = /usr/local/rvm/rubies/ruby-2.0.0-p648/.irbrc
PYTHONUNBUFFERED = 1
PASSENGER_DEBUG_DIR = /tmp/passenger.spawn-debug.XXXXz3l0Qq
MY_RUBY_HOME = /usr/local/rvm/rubies/ruby-2.0.0-p648
USER = nobody
IN_PASSENGER = 1
RACK_ENV = development
PASSENGER_USE_FEEDBACK_FD = true
PATH = /root/.rvm/gems/ruby-2.0.0-p648/bin:/root/.rvm/gems/ruby-2.0.0-p648@global/bin:/usr/local/rvm/rubies/ruby-2.0.0-p648/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:.
WSGI_ENV = development
PWD = /root/NTP
NODE_PATH = /usr/share/passenger/node
NODE_ENV = development
SHLVL = 0
HOME = /nonexistent
RAILS_ENV = development
LOGNAME = nobody
SERVER_SOFTWARE = nginx/1.8.1 Phusion_Passenger/5.0.27
GEM_PATH = /root/.rvm/gems/ruby-2.0.0-p648:/root/.rvm/gems/ruby-2.0.0- p648@global
PASSENGER_APP_ENV = development

jeudi 19 mai 2016

Rails nesting static routes

I have several static pages (About, Contact, Help) that are mapped in the routes.rb file like this:

get 'about', to: 'static#about', as: 'about'
get 'contact', to: 'static#contact', as: 'contact'
get 'help', to: 'static#help', as: 'help'

They are accessed in the layout partial, _footer.html.erb from this code:

<%= link_to "About", 'about_path', :class => '' %>
<%= link_to "Contact", 'contact_path',  :class => '' %>
<%= link_to "Help", 'help_path', :class => '' %>

Everything works fine until I click on the footer links while I'm in a nested route like /users/current/edit (where I might edit my user-profile). For example, when I click on the ABOUT link at the bottom of the page, I would expect to be taken directly to the static#about route at about_path.

However, I am getting an ActionController exception (in development) and a page not found in production. It's trying to map to /users/current/about_path.

Any ideas on how to fix this?

Rspec when retrying Begin - Rescue does not work properly

I need to test the asyncious story, so the maximum time that I need to wait for 5 mins but using retrying I would like to check the results in every 30 seconds and as soon as the test is passed, I would like to end the test. But the code that I wrote;

it "whatever" do
    @sysadmin.update!('Account', Id: @account_id_d, Status: "xyz")
    puts"For the case 2:"
    sleep 30
    begin
        puts"Checking case 2.."
        @account_a[:Status].should eq "xyz" 
        @account_b[:Status].should eq "xyz" 
        @account_c[:Status].should eq "xyz" 
        @account_e[:Status].should eq "xyz" 
        @account_f[:Status].should eq "xyz"
        @account_g[:Status].should eq "xyz"
    rescue Exception => e
        $attempts += 1
        sleep 30
        puts"Sleep Time:#{$attempts}"
        retry if $attempts < 11
        raise Exception if $attempts == 11

    end
end

It does not end the test even if the test is passed and I am getting the terminal output like this;

For the case 2:
Checking case 2..
Sleep Time:1
Checking case 2..
Sleep Time:2
Checking case 2..
Sleep Time:3
Checking case 2..
Sleep Time:4
Checking case 2..
Sleep Time:5
Checking case 2..
Sleep Time:6
Checking case 2..
Sleep Time:7
Checking case 2..
Sleep Time:8
Checking case 2..
Sleep Time:9
Checking case 2..
Sleep Time:10
Checking case 2..
Sleep Time:11

Do you help me to find what is wrong with my code and how can I end the test when it is passed?

Table and column name changes post database switch to postgresql in code

We have a very old application with multiple databases. Recently we decided to make a switch from MSSQL to PostgreSQL. During the process we decided to keep all the table and column names in lower case. This affects our code a lot. We want to go with minimal change approach.

Problems :

  1. Table name changes - We thought of overriding getters and setters for the table_name in model to avoid changes at many places. Creating a module and then including that in all the models was one option. But our setter can't get control because of "ar-octopus" gem. It actually hijacks the setter for table_name. So this approach fails.
  2. We tried mapping dynamic methods like "find_by_UserID" to "find_by_userid" by overriding "method_missing". But dynamic_matchers in activerecord has marked the method as private, so this also doesn't works.

The only option now seems to be refactor the whole code to suit the table and column name changes. But we have used queries, direct column accessing like @person["Name"] in views as well and use of many dynamic functions like mentioned in point 2. So even after refactoring the whole code and testing it completely we wouldn't be sure whether all the code has been updated properly or not.

We want refactoring to be last option. But, don't know any other better way.

mercredi 18 mai 2016

uninitialized constant ActiveRecord::ConnectionAdapters::Mysql2Adapter::NATIVE_DATABASE_TYPES (NameError)

Im having a problem with running my rails server. ive set the abstract_mysql2_adapters at initializer that consist of:

class ActiveRecord::ConnectionAdapters::Mysql2Adapter
NATIVE_DATABASE_TYPES[:primary_key] = "int(11) auto_increment PRIMARY KEY"
end

and it solved my rake db:migrate problem, but when i try to run my rails server it gives me this error.

C:/Users/XXXX/Documents/RoRCmS/simple_cms/config/initializers/abstract_mysql2_adapter.rb:2:in <class:Mysql2Adapter>': uninitialized constant ActiveRecord::ConnectionAda pters::Mysql2Adapter::NATIVE_DATABASE_TYPES (NameError) from C:/Users/John/Documents/RoRCmS/simple_cms/config/initializers/abstract_mysql2_adapter.rb:1:in' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-4.0.0/lib/rails/engine.rb:609:in block (2 levels) in <class:Engine>' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-4.0.0/lib/rails/engine.rb:608:ineach' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-4.0.0/lib/rails/engine.rb:608:in block in <class:Engine>' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-4.0.0/lib/rails/initializable.rb:30:ininstance_exec' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-4.0.0/lib/rails/initializable.rb:30:in run' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-4.0.0/lib/rails/initializable.rb:55:inblock in run_initializers' from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:228:in block in tsort_each' from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:350:inblock (2 levels) in each_strongly_connected_component' from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:431:in each_strongly_connected_component_from' from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:349:inblock in each_strongly_connected_component' from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:347:in each' from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:347:incall' from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:347:in each_strongly_connected_component' from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:226:intsort_each' from C:/Ruby23-x64/lib/ruby/2.3.0/tsort.rb:205:in tsort_each' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-4.0.0/lib/rails/initializable.rb:54:inrun_initializers' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-4.0.0/lib/rails/application.rb:215:in initialize!' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-4.0.0/lib/rails/railtie/configurable.rb:30:inmethod_missing' from C:/Users/John/Documents/RoRCmS/simple_cms/config/environment.rb:5:in <top (required)>' from C:/Users/John/Documents/RoRCmS/simple_cms/config.ru:3:inrequire' from C:/Users/John/Documents/RoRCmS/simple_cms/config.ru:3:in block in <main>' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-1.5.5/lib/rack/builder.rb:55:ininstance_eval' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-1.5.5/lib/rack/builder.rb:55:in initialize' from C:/Users/John/Documents/RoRCmS/simple_cms/config.ru:innew' from C:/Users/John/Documents/RoRCmS/simple_cms/config.ru:in <main>' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-1.5.5/lib/rack/builder.rb:49:ineval' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-1.5.5/lib/rack/builder.rb:49:in new_from_string' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-1.5.5/lib/rack/builder.rb:40:inparse_file' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-1.5.5/lib/rack/server.rb:277:in build_app_and_options_from_config' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-1.5.5/lib/rack/server.rb:199:inapp' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-4.0.0/lib/rails/commands/server.rb:48:in app' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rack-1.5.5/lib/rack/server.rb:314:inwrapped_app' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-4.0.0/lib/rails/commands/server.rb:75:in start' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-4.0.0/lib/rails/commands.rb:78:inblock in ' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-4.0.0/lib/rails/commands.rb:73:in tap' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-4.0.0/lib/rails/commands.rb:73:in' from bin/rails:4:in require' from bin/rails:4:in'

I really need to solve this problem now.. thanks guys.

Rails vendor assets not serving .. no route found error

I am working with ruby 2.2 and rails 4.2.

In my application there are many CSS and JS files that I want to load from the server only when needed.But when whenever I am calling the stylesheet from independent folders in vendor using stylesheet link tag I am getting no route match error

ActionController::RoutingError (No route matches [GET] "/vendor/theme/assets/stylesheets/application.css"):

I have tried adding the routes to "Rails.application.config.assets.paths" but still not working.

I tried using public folder for the same purpose but still not working.

Is it possible to server these assets without precompiling them as only some individual pages require these assets.Kindly suggest.

Carmen-rails how to display the default selected state value?

I've been trying to follow this: Why is carmen-rails not defaulting the saved state and GitHub issue: country_select in nested model doesn't get filled when editing record. But I can't seem to get the code working.

I've added sub_region to pass to the partial but I think the problem is my @country value is nil for some reason when I go to the edit form. When I am selecting the country, my @testcountry.inspect dynamically returns the selected country. When creating a new user, the form works fine. After choosing country, the state field dynamically updates to the relevant select dropdown list.

_subregion_select.html.erb

<div id="order_state_code_wrapper">
  <% parent_region ||= params[:parent_region] %>
  <% sub_region ||= params[:sub_region] %>

  <% @testcountry = Carmen::Country.coded(parent_region) %>

  <% unless parent_region.nil? %>
    <% @country = Carmen::Country.coded(parent_region) %>
  <% end%>

  <%= @testcountry.inspect %>

  <% if @country.nil? %>
    <em>Please select a country above</em>
  <% elsif @country.subregions? %>
    <%= subregion_select(:user, :subdivision, parent_region) %>
  <% else %>
    <%= text_field(:user, :subdivision) %>
  <% end %>
</div>

_form.html.erb

<%= form_for(@user) do |f| %>
  <div class="field">
    <%= f.label :country %><br />
    <%= f.country_select :country, priority: %w(US CA), prompt: 'Please select a country' %>
  </div>

  <div class="field">
    <%= f.label :subdivision, "State/Province" %><br />
    <%= render 'subregion_select', locals: {parent_region: f.object.country, :sub_region => f.object.subdivision } %>
  </div>

  <div class="field">
    <%= f.label :city %><br>
    <%= f.text_field :city %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

users.js.coffee

$(document).on 'ready page:load', ->
  $('select#user_country').change (event) ->
    select_wrapper = $('#order_state_code_wrapper')

    $('select', select_wrapper).attr('disabled', true)

    country = $(this).val()

    url = "/subregion_options?parent_region=#{country}"
    select_wrapper.load(url)

users_controller.rb

def subregion_options
  render partial: 'subregion_select', locals: { parent_region: params[:parent_region], sub_region: params[:sub_region] }
end

Any insight would help, thank you!