vendredi 31 juillet 2015

Strange result from Ruby string to string less than comparison

So I have two strings '5' and '12'. In Ruby (ruby 2.0.0p598 (2014-11-13 revision 48408)) I want to do a comparison on these two to see which is less than the other. If I do '5' <= '12' I get false as a result. Why?

How to limit concerns in routing to certain actions for root but not for namespace - Rails 4

So lets consider the following in routes.rb

  concern :shared_actions do
    resources :courses do
      resources :lessons
    end
    resources :users
  end

my admin namespace has the following

  namespace :admin do
    concerns :shared_actions
    get '', to:'dashboard#index', as: '/'
    resources :lessons
  end

and my root path '/' also shares the same concerns using

concerns :shared_actions

So what i want is,for the root path i want only index and show action for the courses path but in the admin namespace i want to have all actions for courses.

Is there a way to do that without writing explicit code for each case?

Integrating FB Page with Rails

I'm trying to integrate FB page with my new Rails application.

Problems:

  • The Fb Page container is properly rendered only when request is directly from addressbar of client(putting url in addressbar and hit go) OR when request is from one controller to other.

  • When any action of same controller is clicked on website i.e. call from SAME controller, the FB Page block is not rendered properly.

Test it here : Test Link

What I've done is:

  • Added FB JS in application.html.erb
  • And there itself, I'm putting my code for Fb Page.(shown below)

application.html.erb

<!DOCTYPE html>
<html>
<head>
  <title>Forgotten Heroes</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
</head>
<body>

<div id="fb-root"></div>

<!-- FB JAVASCRIPT SDK STARTS -->

<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.4";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

<!-- FB JAVASCRIPT SDK ENDS -->

<div id="header" class="generic">
  Forgotten Heroes
  <div id="main-menu">
    <span class='menu-links'>Home</span>
    <span class='menu-links'>Blogs</span>
    <span class='menu-links'>Trending</span>
    <span class='menu-links'>About Us</span>
  </div>

  <div id="fb-page-like">
    <div class="fb-page" data-href="http://ift.tt/1eFsdao" data-width="350" data-small-header="true" data-adapt-container-width="false" data-hide-cover="false" data-show-facepile="false" data-show-posts="false">
    <div class="fb-xfbml-parse-ignore">
    <blockquote cite="http://ift.tt/1eFsdao">
      <a href="http://ift.tt/1eFsdao">Forgotten Heroes</a>
    </blockquote>
    </div></div>
  </div>

</div>

<%= yield %>

<div id="footer" class="generic">
  &copy; <a href="http://forgottenhero.in" >forgottenhero.in</a>
</div>

</body>
</html>

Associated Id Not saved in database

getflows_controller.rb

    class GetflowsController < ApplicationController
  before_action :set_getflow, only: [:show, :edit, :update, :destroy]
  # GET /getflows
  # GET /getflows.json
  def index
    @getflows = Getflow.all
    @todos = Todo.includes(:getflow)



  end

  # GET /getflows/1
  # GET /getflows/1.json
  def show
    @todos = @getflow.todos

  end

  # GET /getflows/new
  def new
    @getflows = Getflow.all
    @getflow = Getflow.new
  end

  # GET /getflows/1/edit
  def edit
  end

  # POST /getflows
  # POST /getflows.json
  def create
    @getflow = Getflow.new(getflow_params)

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

  # PATCH/PUT /getflows/1
  # PATCH/PUT /getflows/1.json
  def update
    respond_to do |format|
      if @getflow.update(getflow_params)
        format.js 
        format.json { render :show, status: :ok, location: @getflow }
      else
        format.html { render :edit }
        format.json { render json: @getflow.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /getflows/1
  # DELETE /getflows/1.json
  def destroy
    @getflow.destroy
    respond_to do |format|
      format.html { redirect_to getflows_url, notice: 'Getflow was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def getflow_params
      params.require(:getflow).permit(:name, :title, :completed, :group_id)
    end
end

groups_controller.rb

    class GroupsController < ApplicationController
  before_action :set_group, only: [:show, :edit, :update, :destroy]

  # GET /groups
  # GET /groups.json
  def index
    @groups = Group.all

  end

  # GET /groups/1
  # GET /groups/1.json
  def show
    @getflows = @.group.getflows
  end

  # GET /groups/new
  def new
    @group = Group.new
    @getflows = Getflow.all
  end

  # GET /groups/1/edit
  def edit
  end

  # POST /groups
  # POST /groups.json
  def create
    @group = Group.new(group_params)

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

  # PATCH/PUT /groups/1
  # PATCH/PUT /groups/1.json
  def update
    respond_to do |format|
      if @group.update(group_params)
        format.html { redirect_to @group, notice: 'Group was successfully updated.' }
        format.json { render :show, status: :ok, location: @group }
      else
        format.html { render :edit }
        format.json { render json: @group.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /groups/1
  # DELETE /groups/1.json
  def destroy
    @group.destroy
    respond_to do |format|
      format.html { redirect_to groups_url, notice: 'Group was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

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

group.rb

    class Group < ActiveRecord::Base
    has_many :getflow
end

getflow.rb

    class Getflow < ActiveRecord::Base
    has_many :todos
    belongs_to :group
end

schema.rb

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

  create_table "events", force: :cascade do |t|
    t.string   "title",      limit: 255
    t.string   "color",      limit: 255, default: "blue"
    t.datetime "end"
    t.datetime "start"
    t.datetime "created_at",                              null: false
    t.datetime "updated_at",                              null: false
  end

  add_index "events", ["end"], name: "end", unique: true, using: :btree
  add_index "events", ["start"], name: "start", unique: true, using: :btree

  create_table "getflows", force: :cascade do |t|
    t.string   "name",       limit: 255
    t.string   "title",      limit: 255
    t.boolean  "completed",  limit: 1
    t.datetime "created_at",             null: false
    t.datetime "updated_at",             null: false
    t.integer  "group_id",   limit: 4
  end

  create_table "groups", force: :cascade do |t|
    t.string   "name",       limit: 255
    t.datetime "created_at",             null: false
    t.datetime "updated_at",             null: false
  end

  create_table "meetings", force: :cascade do |t|
    t.string   "name",       limit: 255
    t.datetime "starts_at"
    t.datetime "created_at",             null: false
    t.datetime "updated_at",             null: false
  end

  create_table "todos", force: :cascade do |t|
    t.text     "content",    limit: 65535
    t.integer  "order",      limit: 4
    t.boolean  "done",       limit: 1
    t.datetime "created_at",               null: false
    t.datetime "updated_at",               null: false
    t.integer  "getflow_id", limit: 4
  end

end

I have two models 1.Getflow 2.Group

Here i am using belongs_to, has_many association between those model in rails 4.

But group_id is not saved in getflows model database.

If i keep @group = Group.find(params[:id]) in getflows_controller index then it says Couldn't find Group with 'id'=

Please help me how to save it.

jeudi 30 juillet 2015

has_many :through how it works?

First of all let me say that I come from oldschool php framework and outdated practices that I'm struggling to undo them. When the PHP I found situations N-N I simply created a new table and was 1-N relationship with this new table. Example:

tbl_users

tbl_posts

Relationship:

tbl_users N-N tbl_posts

So I just created in the new table and made 1-N relationship (common has_many). Example:

tbl_users 1-N tbl_like_posts

tbl_posts 1-N tbl_like_posts

I do not know if there was something equivalent and I did not use because I was never charged. But the reality is that I've looked on the has_many: through and fail to make it into my head. Why can I not do what I did before? What: through is special? What it will ease me? I even understand how to use, but did not understand why to use.

I'm sorry if the question was kind of silly, but I'm trying to drop PHP addictions and learn the rails correctly.

Rails Users updating information in custom routes?

Not sure how to title my question...

My intent is that users will have a list of items (and only the current_user can edit this list)

class Item < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :items
end

I have a Users controller (note: I'm also using devise gem, but created a separate Users Controller)

class UsersController < ApplicationController
  load_and_authorize_resource
  def show
    @user = User.find(params[:id])
  end

  def list
    @user.items.build
  end

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

    def user_params
      params.require(:user).permit(
        items_attributes: [:user_id, :item, :name, :_destroy]).merge(user_id: current_user.id)
    end
end

Right now I have set up routing

get 'users/:id/list', to: 'users#list', as: :list

Which gives me this: localhost:3000/users/1/list

Theoretically, this should be the show view... where it'll populate the list of items for user id: 1.

I want to be able to do localhost:3000/list/edit So the user can update this list.

My form in views/users/list.html.erb (I'm using cocoon gem for help with nested forms).

<%= simple_form_for @user do |f| %>

  <%= f.simple_fields_for :items do |i| %>
    <%= f.text_field :item %>
    <%= f.text_field :name %>
  <% end%>

  <%= link_to_add_association 'add item', f, :items %>
  <%= f.button :submit %>

<% end %>

I know my form is in my list.html.erb where it'll populate all the items, but I'm just doing this for testing purposes.

How do I update the form to save into items database and its associated with the current user?

Rails flash message not showing up

I'm trying to verify a DEA number by calling an action that calls a verify gem.

Here's the view

  <label for="prescriber_dea_number">DEA number</label>
  <%= text_field_tag :prescriber_dea_number %>
  <%= link_to "Verify DEA number", dea_verification_insight_reports_prescriber_activity_with_patient_request_index_path remote:true %>

Here's the controller action

def dea_verification
dea = params[:prescriber_dea_number]
respond_to do |format|
  if PmpCheckdigit.dea_number?(dea)
    #flash confirmation
    flash[:notice] = "DEA number is valid"
    format.js
  else
    #flash error
    flash[:error] = "DEA number is invalid, Expected something similar to 'AB12345678'"
    format.js
  end
end
end

When the button to Verify is clicked, no flash message appears on the page

Here's what I get in the log

Started GET "/insight_reports/prescriber_activity_with_patient_request/dea_verification" for 127.0.0.1 at 2015-07-30 17:15:34 -0400

AbstractController::ActionNotFound (The action 'show' could not be found for InsightReports::PrescriberActivityWithPatientRequestController):

How to customize version filename in Carrierwave?

I have a strange issue. I am trying to use master branch of carrierwave with Rails 3.2.xx project. I need to customize filenames of the versions. But when I add full_filename method in the version block, my original file also gets reduced to the dimensions specified for version.

When I remove full_filename method, it all works as expected, but thumb filename has thumb_ prefix which I don't want.

Is there a new way to customize version filenames. I have been using this way successfully in 0.10.0 and before.

Below is my uploader. This is a generated uploader with store_dir overrides.

class TestUploader < CarrierWave::Uploader::Base

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

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

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

  # Create different versions of your uploaded files:

  version :thumb do
    process :resize_to_fit => [200, 200]

    def store_dir
      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}/#{version_name}"
    end

    def full_filename(for_file = model.logo.file)
      super(for_file).sub(version_name.to_s + '_', '')
    end
  end

end

Any ideas? All I need to do is to remove version_name part from its filename, since I am saving the versions in separate folders. I searched through Wiki and internet, but couldn't find a new way of doing this.

Unable to install 0ci8 library on ruby 2.2.2p95 (windows 7) and connect to Oralce

i have looked into many Forums also in Ruby's one, am not able to install oci8. its shows following error..

D:\Ruby_WS>gem install ruby-oci8 -v 2.0.3 Building native extensions. This could take a while... ERROR: Error installing ruby-oci8: ERROR: Failed to build gem native extension. C:/Ruby22-x64/bin/ruby.exe -r ./siteconf20150730-4004-l0oo7f.rb extconf.rb checking for load library path... PATH... checking C:\Ruby22-x64\bin... no checking D:\app\BGH39173\product\11.2.0\client_1... yes D:/app/BGH39173/product/11.2.0/client_1/oci.dll looks like an instant client. checking for cc... ok checking for gcc... yes checking for LP64... no checking for ruby header... * extconf.rb failed * Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options.

Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=C:/Ruby22-x64/bin/$(RUBY_BASE_NAME) --with-instant-client --without-instant-client C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-oci8-2.0.3/ext/oci8/oraconf.rb:596:in check_ruby_header': Runti from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-oci8-2.0.3/ext/oci8/oraconf.rb:552:ininit' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-oci8-2.0.3/ext/oci8/oraconf.rb:1001:in initialize' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-oci8-2.0.3/ext/oci8/oraconf.rb:343:innew' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-oci8-2.0.3/ext/oci8/oraconf.rb:343:in `get'

from extconf.rb:18:in `'

Error Message: uninitialized constant OraConf::Config Backtrace: C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-oci8-2.0.3/ext/oci8/oraconf.rb:596:in check_ruby_header' C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-oci8-2.0.3/ext/oci8/oraconf.rb:552:ininit' C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-oci8-2.0.3/ext/oci8/oraconf.rb:1001:in initialize' C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-oci8-2.0.3/ext/oci8/oraconf.rb:343:innew' C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-oci8-2.0.3/ext/oci8/oraconf.rb:343:in `get'

extconf.rb:18:in `'

See: * http://ift.tt/1Iu3YYK * http://ift.tt/1DSaJhM

extconf failed, exit code 1

Gem files will remain installed in C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-oci8-2.0.3 for inspection. Results logged to C:/Ruby22-x64/lib/ruby/gems/2.2.0/extensions/x64-mingw32/2.2.0/ruby-oci8-2.0.3/gem_make.ou

D:\Ruby_WS>ruby -version ruby 2.2.2p95 (2015-04-13 revision 50295) [x64-mingw32] -e:1:in <main>': undefined local variable or methodrsion' for main:Object (NameError)

please help me..

How to assign value to field in rails_admin?

I am using RailsAdmin gem and I have some virtual attributes in model. I made input fields in rails_admin.rb initializer for that attributes like this:

  field :name, :string do
    formatted_value do
      "123123213213"
    end
    read_only false
  end

I tried to assign value to field like this but nothing is happening. Can anyone tell me where I am wrong?

How to have same routes with and without namespace - rails 4

So, i am making a custom admin panel in the admin namespace.

and i have a resources courses in it.

what i don't know is how can i have the same routes shared between the namespace and without the namespace

eg: localhost:3000/admin/courses & localhost:3000/courses

the controllers ok can be different

the thought is that its not really DRY paradigm if i have both resources for the same route

namespace admin do
   resources :courses
end

and just

resources :courses

Is there a way to have one resource and be shared between namespace and without namespace or the example above is the way to go?

How to have same routes with and without namespace - rails 4

So, i am making a custom admin panel in the admin namespace.

and i have a resources courses in it.

what i don't know is how can i have the same routes shared between the namespace and without the namespace

eg: localhost:3000/admin/courses & localhost:3000/courses

the controllers ok can be different

the thought is that its not really DRY paradigm if i have both resources for the same route

namespace admin do
   resources :courses
end

and just

resources :courses

Is there a way to have one resource and be shared between namespace and without namespace or the example above is the way to go?

How to share image on Facebook using fb_graph gem in rails

I want to share image on Facebook using fb_graph gem but i don't understand the exact procedure that how to implement in localhot.

I not use "localhost:3000" but i used "lvh.me:3000" because in my application i used subdomain concept so when user login then url is change to "xyz.lvh.me:3000/"

in my controller :-

class FbShareController < ApplicationController

def auth
    @album = current_photographer.albums.friendly.find(params[:album_id])
    @album_photo = @album.album_photos.friendly.find(params[:photo_id])
    cookies["title"] = { :value => @album_photo.photo_title, :expires => 1.minute.from_now }
    cookies["url"] = { :value => @album_photo.photo.url(:original), :expires => 1.minute.from_now }
    @client = client
    redirect_to @client.authorization_uri(
      :scope => [ :user_photos, :publish_pages, :user_posts]
    )
  end

  def callback
    # @album = current_photographer.albums.friendly.find(params[:album_id])
    @client = client
    @client.authorization_code = params[:code]
    access_token = @client.access_token! :client_auth_body # => Rack::OAuth2::AccessToken

    me = FbGraph::User.me(access_token)

    title = cookies["title"]
    url = cookies["url"]

    me.feed!(
        :message =>  title,
        :link => url,
        :name => title,
        :picture => url
    )

    redirect_to album_path(@album)
  end

  private

  def client
    if Rails.env.development?
      key = "xxxxxxxxxxxxxxx"
      secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    else
      key = "xxxxxxxxxxxxxxx"
      secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    end
    fb_auth = FbGraph::Auth.new(key, secret)
    client = fb_auth.client
    client.redirect_uri = "http://#{request.host_with_port}/fb_share/callback"
    client
  end
end

I create app on my Facebook named lvh.me:3000 and Facebook provide me two IDs like User id and App id and also provide App secret key.

So which combination i have to use in my controller ?

fb_auth = FbGraph::Auth.new(User_id, secret) OR

fb_auth = FbGraph::Auth.new(App_id, secret)

However, i already used both combination but i get following error:-

{
   "error": {
      "message": "Error validating application. Cannot get application info due to a system error.",
      "type": "OAuthException",
      "code": 101
   }
}

Whats wrong with my code i don't know.

I don't know that how to set configuration in facebook for this.

I need step by step solution if any one have because i am totally new in rails.

Any one have proper solution or steps because i already spent much more time behind this but i have no idea what to do.

Thanks in advance.

Ruby on Rails persistently store Hash from CSV

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

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

culper_hash = {}

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

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

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

My thoughts:

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

or

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

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

Redmine How to display application menu under specific top menu?

I am working on leave management system plugin so want to show application menu under lms menu.... here i past my init file code

 menu :top_menu, :leave_transactions, { :controller => 'dashboard', :action => 'index' }, :caption => 'LMS' , :if => Proc.new { User.current.logged? }
    menu :application_menu, :dashboard, { :controller => 'dashboard', :action => 'index' }, :caption => 'Dashboard' , :if => Proc.new { User.current.logged? }
    menu :application_menu, :leave_transactions, { :controller => 'leave_transactions', :action => 'index' }, :caption => 'Apply Leave' , :if => Proc.new { User.current.logged? }
    menu :application_menu, :holiday_informations, { :controller => 'holiday_informations', :action => 'index' }, :caption => 'Holiday' , :if => Proc.new { User.current.logged? }

Its working for me but application menu display all over menu. so i want to avoid this and when I click on lms menu that time application menu display..please help me

Not able to start the rails server

I am new to Ruby, am trying to setup Ruby jruby and Ruby on Rails.

I installed bundler and using "rails server -e qa" command in my command prompt. I am getting:

pageant.rb:1:in `require': cannot load such file -- dl/import (LoadError).

Ruby22-x64/lib/ruby/gems/2.2.0/gems/activesupport-3.2.21/lib/active_support/values/time_zone.rb:270: warning: circular argument reference - now
Ruby22-x64/lib/ruby/gems/2.2.0/gems/mongoid-3.1.6/lib/mongoid/persistence/atomic/operation.rb:74: warning: circular argument reference - field
Ruby22-x64/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh/authentication/pageant.rb:1:in `require': cannot load such file -- dl/import (LoadEr
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh/authentication/pageant.rb:1:in `<top (required)>'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh/authentication/agent/socket.rb:5:in `require'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh/authentication/agent/socket.rb:5:in `<top (required)>'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh/authentication/agent.rb:22:in `require'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh/authentication/agent.rb:22:in `<top (required)>'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh/authentication/key_manager.rb:4:in `require'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh/authentication/key_manager.rb:4:in `<top (required)>'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh/authentication/session.rb:4:in `require'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh/authentication/session.rb:4:in `<top (required)>'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh.rb:11:in `require'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/net-ssh-2.9.2/lib/net/ssh.rb:11:in `<top (required)>'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/net-sftp-2.1.2/lib/net/sftp.rb:1:in `require'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/net-sftp-2.1.2/lib/net/sftp.rb:1:in `<top (required)>'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/runtime.rb:85:in `require'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/runtime.rb:85:in `rescue in block in require'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/runtime.rb:68:in `block in require'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/runtime.rb:61:in `each'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/runtime.rb:61:in `require'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler.rb:134:in `require'
     from D:/Ruby_WS/config/application.rb:7:in `<top (required)>'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-3.2.21/lib/rails/commands.rb:53:in `require'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-3.2.21/lib/rails/commands.rb:53:in `block in <top (required)>'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-3.2.21/lib/rails/commands.rb:50:in `tap'
     from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-3.2.21/lib/rails/commands.rb:50:in `<top (required)>'
     from script/rails:6:in `require'
     from script/rails:6:in `<main>'

change type in polymorphic association in rails

I am new to rails and I'm using rails Polymorphic association and I ran into a problem I have two models EmployeeTable and ProductTable. Both have some picture in Picture Model

class Picture < ActiveRecord::Base
   belongs_to :imageable, polymorphic: true
end

class EmployeeTable < ActiveRecord::Base
   has_many :pictures, as: :imageable
end

class ProductTable < ActiveRecord::Base
  has_many :pictures, as: :imageable
end

there are two column in Picture imagable_id and imagable_type. When I create an entry in table it stores imagable_type as either "EmployeeTable" or "ProductTable". Can I change these name to any different Names like "employee" and "product".

Thanks in advance

mercredi 29 juillet 2015

What could be possible test cases for this controller action and how can i handle if else conditions. Using minitest framework in RubyonRails

I am new to writing test cases and I cant figure out the scenarios of writing tests. For example there are too many if else conditions in controller how would I write cases for these conditions. Below is my registration controller. I am using rails minitest framework for rails 3.2.1 version.

def create
    invitation_token = params["invitation_token"]
    #Check if the user exists yet based on their e-mail address.
    user = User.find_by_email(params[:user][:email])
    omni = session[:omniauth] || params[:omniauth]

    theme_id = nil
    theme_layout_id = nil
    theme_style_id = nil

    begin
        omni = JSON.parse omni if omni
    rescue => e
      # if we got here, the omni is invalid!!
      return redirect_to '/login'
    end

     #Did we find a user yet? If not, perform the following.
    if user.nil? && !invitation_token.present?
        client  = Client.find_or_create_by_name(name: params[:user][:username])
        #p client.errors
        if client.present?
            user    = User.new
            app_url = ApplicationUrl.find_by_domain_url(request.host_with_port)

            user.apply_omniauth(omni)
            user.email = params[:user][:email]
            user.username = params[:user][:username]
            user.client_id = client.id

            #Assign the user/client the Free plan by default.
            plan = ClientPlan.find_or_create_by_client_id(client_id: client.id, plan_id: 1, plan_billing_cycle_id: 1, start_date: Date.today, is_paid: 1, isactive: 1)

            #Set the client settings to the defaults for a Free (non business plan) user.
            ClientSetting.create(client_id: client.id, is_billboard_enabled: 0, is_tweetback_enabled: 0, is_conversations_enabled: 0)

            #Set the client environment link.
            ClientsEnvironment.create(environment_id: environment.id, client_id: client.id)

            unless params[:user][:theme_id].nil?
                theme_id = params[:user][:theme_id]
                puts "theme id: " + theme_id.to_s
            end
            unless params[:user][:theme_layout_id].nil?
                theme_layout_id = params[:user][:theme_layout_id]
                puts "theme layout id: " + theme_layout_id.to_s
            end
            unless params[:user][:theme_style_id].nil?
                theme_style_id = params[:user][:theme_style_id]
                puts "theme style id: " + theme_style_id.to_s
            end

            #Create an application for the client.
            Application.find_or_create_by_client_id(
                client_id: client.id,
                name: params[:user][:username],
                callback_url: "#{request.host_with_port}",
                application_url_id: app_url.id
              )

            #Create the default feed for the client.
            Feed.find_or_create_by_client_id(
                client_id: client.id,
                name: 'My Feed',
                token: SecureRandom.uuid,
                theme_id: theme_id,
                theme_style_id: theme_style_id,
                theme_layout_id: theme_layout_id
            )
          if user.save
            #Remember me?
            if params[:remember_me]
              user.remember_me!
            end

          client = user.client
          client.update_attribute(:owner_user_id, user.id)

          schedule_reminder_email(user)

                #Create the users Profile
            Profile.find_or_create_by_user_id(
              user_id: user.id,
              fullname: params[:user][:fullname],
              username: params[:user][:username]
            )
            record_event_profile(user,params[:user][:fullname],params[:remember_me])
          end
        end
    elsif user.nil? && invitation_token.present?
      user = User.new
      invite = Invite.find_by_token(invitation_token)
      if invite.present?
        client  = invite.client
        user.apply_omniauth(omni)
        user.email = params[:user][:email]
        user.username = params[:user][:username]
        user.client_id = client.id
        user.can_curate = false
        user.can_publish = false
        if user.save
          #Remember me?
          if params[:remember_me]
            user.remember_me!
          end

          #Create the users Profile
          Profile.find_or_create_by_user_id(
            user_id: user.id,
            fullname: params[:user][:fullname],
            username: params[:user][:username]
          )
          record_event_profile(user,params[:user][:fullname],params[:remember_me])
          invite.update_attributes({invite_accepted_at: Time.now, name: user.profile.try(:fullname)})
        end
      else
        return redirect_to root_path
      end
    else
      #If a user already exists for the email address then this must just be a new social network account for this user.
      token = omni['credentials']['token']
        token_secret = ""
        user.relatednoise_authentications.create!(
            provider: omni['provider'],
            uid: omni['uid'],
            token: token,
            token_secret: token_secret
        ) if user.present?
    end

    #Create an entry in Socialnetworkaccounts for this user to associate them to their social login/account.
    create_sna(omni, user)
    #SignupNotifier.init_notify(user).deliver
    begin
        ApiConnector.new("#{API_URL}/notify_us/#{user.id}")
    rescue => e
        Airbrake.notify_or_ignore(e, {})
    end

    unless user.new_record?
        session[:omniauth] = nil
        session[:omniauth_auth] = nil
        #reset_invite_token
    end

    session[:user_id] = user.id
    record_event_signup(user)

    back_if_coming_from_wix(params[:wix_appid], user)

    sign_in_and_redirect user if !params[:wix_appid].present?
  end

so far i have written this. Not sure if this is the way to write test cases.

require 'test_helper'

class RegistrationsControllerTest < ActionController::TestCase
  fixtures :users

  def setup
    @params = {"omniauth"=>"{\"provider\":\"twitter\",\"uid\":\"167003011\",\"credentials\":{\"token\":\"167003011-ZqnlBsCZlFjymanQ6gQ2ggD7a2tAESuUVlygw0WN\",\"secret\":\"idVWQgR79HOKmZfuNtVtxvzWzGH5plJlxdEksxyuHgH5S\"}}","user"=>{"fullname"=>"Tommy", "email"=>"Tom@moody.com", "username"=>"tommy", "theme_id"=>"", "theme_style_id"=>"", "theme_layout_id"=>""}}
    @invite = invites(:arvind_invite)
  end

  def test_new
    get :new
    assert_response :success
  end

def test_create_for_client_plan
  assert_difference ->{ ClientPlan.count }, +1 do
    post :create, @params
  end
end

def test_create_for_client_setting
  assert_difference ->{ ClientSetting.count }, +1 do
    post :create, @params
  end
end

def test_create_for_client_environment
  assert_difference -> {ClientsEnvironment.count}, +1 do
    post :create, @params
  end
end

def test_create_for_application
  assert_difference -> {Application.count}, +1 do
    post :create, @params
  end
end

def test_create_for_user
  assert_difference -> {User.count}, +1 do
    post :create, @params
  end
end

def test_create_for_feed
  assert_difference -> {Feed.count}, +1 do
    post :create, @params
  end
end

def test_create_for_profile
  assert_difference -> {Profile.count}, +1 do 
    post :create, @params
  end
end

def test_create_for_sna
  assert_difference -> {Socialnetworkaccount.count}, +1 do
    post :create, @params
  end
end

def test_create_for_user_with_invitation
  assert_difference -> {User.count}, +1 do
    post :create, @params.merge({invitation_token: @invite.token})
  end
end

end

This is my test helper file.

ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase
  include Devise::TestHelpers
  # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
  #
  # Note: You'll currently still have to declare fixtures explicitly in integration tests
  # -- they do not yet inherit this setting
  fixtures :all

  def host_with_port
    @request.host_with_port = "localhost:3000"
  end

  # Add more helper methods to be used by all tests here...
end

update user image using best_in_place in rails3.2

How can i change user image along with user name using best_in_place select?

<%= image_tag @assignment.user.avatar %>

<%= best_in_place @assignment, :user_id, as: :select, :collection => User.all.collect{|u| [u.id, u.first_name]} %>

on select user is updating but not the image.

Thanks

Using SendCloud with 'X-SMTPAPI' in Rails

I hope this post will help someone.I need to use SendCloud to send emails through smtp.At the begin i add header in ActionMailer:

headers["X-SMTPAPI"] = JSON.dump({"to" => emails, "sub" => {"%name%" => names}})

But it can't work, and i also can't receiver the return error code through Rails.Then i find the way through communication with their support:

headers["X-SMTPAPI"] = Base64.encode64(JSON.dump({"to" => emails, "sub" => {"%name%" => names}}))

But it also can't work correctly.Then i compare the generated headers["X-SMTPAPI"] with the sent headers["X-SMTPAPI"], and found Rails insert '\n' in it for format.In the end, Mail gem convert the '\n':

def encode_crlf(value)
  value.gsub!(CR, CR_ENCODED)
  value.gsub!(LF, LF_ENCODED)
  value
end

So, if i want it's success, i need to do like this:

headers["X-SMTPAPI"] = Base64.encode64(JSON.dump({"to" => emails, "sub" => {"%name%" => names}})).gsub!(/\n/,'')

Wow, i can send 'x-smtpapi' header in Rails successfully!

How can I load partial view with ajax dynamically?

It creates new comment record but it won't reload partial:(
It just shows a white blank page right after I clicked on submit button.
Why? and How can I fix this?

views/movies/show.html.erb

<div id="partial">
    <%= render 'movies/comment' %>
</div>

<form action="/comments" method="post" data-remote="true" >
    <input type="text" name="body" id="input" />
    <button type="submit" >Submit</button>
    <input type="hidden" name="video_id" value="<%= params[:uid] %>">
</form>

/config/routes.rb

resources :comments
get "movies/:uid/refresh" => 'movies#refresh'

controllers/comments_controller.rb

def create
    if @user = User.find_by_twitter_id(session[:id])
    else
        @user = User.new
        @user.twitter_id = session[:id]
        @user.save
    end

    if @movie = Movie.find_by_uid(params[:video_id])
    else
        @movie = Movie.new
        @movie.uid = params[:video_id]
        @movie.save
    end

    @comment = Comment.build_from(@movie, @user.id, params[:body]) 
    @comment.save

    flash[:notice] = "Posted!"

    respond_to do |format|  
        format.js do
            render 'movies/' + @movie.uid + '/refresh'
        end 
    end     
end

controllers/movies_controller.rb

def refresh
    @movie = Movie.find_by_uid(params[:uid])
    @comments = @movie.comment_threads.order("created_at DESC")

    respond_to do |format|
        format.js 
    end
end

def show
    if @movie = Movie.find_by_uid(params[:uid]) 
        @comments = @movie.comment_threads.order("created_at DESC")
    end

    respond_to do |format|
        format.html # show.html.erb
        format.json { render json: @movie }
    end
end

views/movies/refresh.js.erb

$('#partial').html("<%= j(render(:partial => 'movies/comment')) %>");
$('#input').val('');

views/movies/_comment.html.erb

<% if @comments %>
    <% @comments.each do |comment| %>
        <%= comment.id %>:<%= comment.body %><br />
    <% end %>
<% end %>

How to check rails params hash from url query parameter contains double quoted string?

I created a GET endpoint to serve an API using rails. I want to be able to check for when the user passes double quotes for the query parameter in the url.

So for example the user could call the below endpoint by passing the query parameter with double quotes or no quotes. My application is expected to behave differently if the double quotes are found in the query params..

localhost:8080/company/data.json?q="America Online in UK"&size=10

Now the user can also call the endpoint with no double quotes like this:

localhost:8080/company/data.json?q=America+Online+in+UK&size=10

OR

localhost:8080/company/data.json?q=AOL&size=10

How do I handle the above use-cases in a rails controller with respect to spaces and double quotes?

Ruby on Rails 3: Streaming data and catching exception

I'm streaming data using the following approach:

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

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

Torquebox/Jboss error page.

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

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

Use same routing for subdomain as for simple domain request

I have a live server say www.test.com and a development server with subdomain, like dev.test.com, but I want the same routing for both. I can not use routing for development server.

Is it possible to write some code in before filter in ApplicationController?

Firefox drop down menu not showing current setting

TL;DR A drop down menu is always showing the same selection (before opening the menu) for Firefox alone. Other browsers show the current saved setting, but Firefox does not.

I have a settings page where users can choose their timezones. The user opens the drop down menu and selects their time zone, then clicks the button "Apply"

When the user does this, the page is reloaded, and the (previously saved) timezone shows as the selection for the drop down menu.

So the steps to updating your timezone go like this

  • Dropdown menu shows "UCT"
  • Open the drop down menu and select "Eastern Time"
  • Click Apply
  • Page reloads and drop down shows "Eastern Time" for all browsers other than Firefox

Is this a Firefox bug? I've turned off accelerating graphics, but this didn't resolve the issue.

i am migrating an application from rails 2.3 to rails 3.1, most of it is done but there is a issue, when the session get expired and i reload the page instead of redirecting me to login page i am getting a error

undefined method `size' for ActionDispatch::Cookies::CookieJar:0x007fa415c12670>

here is the code where i am getting the error

def access_denied
  respond_to do |accepts|
    accepts.html do
      test_location
      if cookies.size==0 && request.host == "somedomain.com"
        redirect_to "/cookies_disabled.html"
      else
        redirect_to new_session_url
      end
    end
    accepts.js do
      render :text => "window.location.href = '#{new_session_url}';"
    end
  end
  false
end  

any help will be appriciated, Thanks.

mardi 28 juillet 2015

before_create is not called on model.create

I have thiw code:

class Project < ActiveRecord::Base
    acts_as_paranoid

    belongs_to :user
    belongs_to :organization
    accepts_nested_attributes_for :organization


    attr_accessible :name, :permalink, :organization_id, :user_id

    validates_length_of :name, :minimum => 4
    validates_presence_of   :permalink
    validates_uniqueness_of :permalink, :case_sensitive => false, :scope => :deleted_at


    validates_presence_of :user        
    validates_presence_of :organization

    before_create :generate_permalink

    protected

    def generate_permalink
      binding.pry
      self.permalink = "123456789"
    end    

end

When I call in ProjectsController#create

p = Project.new
p.name = "abcdef"
p.save

App doesn't stop on binding.pry in generate_permalink, and the project is not valid and is not saved because permalink == nil. Why generate_permalink method is not called?

Thanks

Migration to add enum column in rails3 and enumerated_attribute

I need a migration to add column of type enum in rails 3. I will be using enumerated_attribute gem.

I generated a migration to add the column:

rails generate migration addUsage_reports_accessToClientParam usage_reports_access:enum

Now I need to set up the values for the enum and set the default value. Here is the generated migration:

class AddUsageReportsAccessToClientParam < ActiveRecord::Migration
  def self.up
    add_column :client_params, :usage_reports_access, :enum
  end

  def self.down
    remove_column :client_params, :usage_reports_access
  end
end

Thanks

Rails Engines: How to generate a controller for Rails engine?

We have three Rails engines maintained in a single application. They are placed in vendor folder,

vendor/
   - Engine1
   - Engine2
   - Engine3

How can I generate controller for Engine1 from my root folder as we normally create controllers? For example,

> rails generate controller Engine1:users

Note:- I could create controller by moving around the folders. That is move to Engine1 folder from root app and generate controller, which works fine. But every time moving around from my root app and generating gets bit hard.

How to properly mix in a Rails helper

I'm trying to add some custom behavior to I18n. Since we want this behavior to be performed in I18n itself as well as the Rails TranslationHelper before their respective translate methods, I've created the following module in lib/translate_extension.rb:

module TranslateExtention
  def new_translate(*args)
    ...

    translate(...) 
  end
end

In config/initializers/i18n.rb the following is working:

module I18n
  extend TranslateExtention
end

However I'm having trouble getting it added as a helper. The following in config/initializers/translation_helper.rb is not doing the trick:

module ActionView
  module Helpers
    module TranslationHelper
      include TranslateExtention
    end
  end
end

I keep getting told that new_translate is not defined for my views.

This is being done on Rails 3.2.22

Rails: is twitter typeahead conflicts client side validation?

I am using client side validation(v3.0.13) gem in my rails(v3.0.20) app. Recently I added twitter's typeahead.js(v0.10.2) for auto suggest.

I have a model named Insurance and the column 'name' is mandatory. When I submit a form with these two js files loaded, I get javascript error Cannot read property 'presence' of undefined in browser console. After this error, other javascript code is failed to run, for example If I put a alert in form submit function, its not working.

Model

insurance.rb

    class Insurance < ActiveRecord::Base
        validates :name, :presence =>  { :message => "Must be filled" }
    end

form.html.erb

    <%= javascript_include_tag "rails.validations", "typeahead" %>
    <%= stylesheet_link_tag "typeahead"%>

    <%= form_for @insurance, :validate => true, :html => {:id => 'insurance_form', :class=>"form-horizontal"} do |f| %>
    <div class="control-group">
        <%= f.label :name, :class=>"control-label" %>
        <div class="controls">
            <%= f.text_field :name, :class =>"input-medium typeahead" %>
        </div>
    </div>
    ...
    <% end %>

And my javascript code

    var insurance_names = ["aaa", "bbb", "ccc"];

    var substringMatcher = function(strs) {
      return function findMatches(q, cb) {
        var matches, substringRegex;
        matches = [];
        substrRegex = new RegExp(q, 'i');
        $.each(strs, function(i, str) {
          if (substrRegex.test(str)) {
            matches.push({ value: str });
          }
        });     
        cb(matches);
      };
    };

    $('.typeahead').typeahead({
      hint: true,
      highlight: true,
      minLength: 1
    },
    {
      name: 'insurance_names',
      source: substringMatcher(insurance_names)
    }).on('typeahead:selected', function($e, datum){
        $(this).trigger('change');
    });

If I comment the model validation code and then submit the form, then there is no javascript error. And also without this typeahead.js client side validation is working fine.

Can anyone help me to solve this problem?

SELECT "categories".* FROM "categories" WHERE "categories"."ancestry" IS NULL

I made a Categories model using Ancestry gem.

When i try to create a new Item I receive this error. Im creating the item in my views/items/New template

ERROR IS FROM THE CONSOLE. In the browser it just says "Your item didn't save"

SELECT "categories".* FROM "categories" WHERE "categories"."ancestry" IS NULL

Anyone know how to this error fix? I've tried for a few hours can't figure it out.

views/items/new.html.erb

<div class="container">
  <div class=“row”>
    <div class="col-md-6 col-md-offset-3">
      <div class="panel panel-primary">
        <div class="panel-body">
          <%= simple_form_for @item, html: { multipart: true } do |f| %>
            <%= f.input :image%>
            <%= f.collection_select :category, Category.order(:name), :id, :name, include_blank: true, :prompt => "Select One Category" %>
            <%= f.input :title%>
            <%= f.input :price %>
            <%= f.input :description %>
            <%= f.button :submit, "Create new item", class: "btn btn-primary" %>
          <% end %>
        </div>
      </div>    
    </div>
  </div>
</div>

Item.Controller

class ItemsController < ApplicationController
  before_action :correct_user_edit,   only: [:edit, :update, :destroy]

  def index
    @item = @user.items.paginate(page: params[:page])
  end

  def new
    @item = Item.new
  end

  def home
    @items = Item.paginate(page: params[:page])
  end

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

  def show
    @item = Item.find(params[:id])
  end

  def update
    @item = Item.find(params[:id])
    if @item.update(item_params)
       redirect_to @item
       flash[:success] = 'Item was successfully updated.'
    else
      render "edit"
    end
  end

  def create
    @item = current_user.items.build(item_params)
    if @item.save
      redirect_to @item
      flash[:success] = "You have created a new item"
    else
      flash[:danger] = "Your item didn't save"
      render "new"
    end
  end

  def destroy
    Item.find(params[:id]).destroy
    flash[:success] = "Item deleted"
    redirect_to users_url
  end

  private

    def item_params
      params.require(:item).permit(:title, :categories, :price, :description, :image)
    end

    #Check to see if user can edit item.
    def correct_user_edit
      if @item = current_user.items.find_by(id: params[:id])
      else
        flash[:danger] = "You can't edit that item"
        redirect_to root_url if @item.nil?
      end
    end

end

Category Model

class Category < ActiveRecord::Base
    has_ancestry
    has_many :items
end

Item Model

class Item < ActiveRecord::Base
    belongs_to :user
    belongs_to :category
    validates :category, presence: true
    validates :title, presence: true, length: { maximum: 30 } 
    validates :price, presence: true
    validates :description, presence: true, length: { maximum: 2000 }
    validates :user_id, presence: true
    has_attached_file :image, styles: { large: "600x600", medium: "250x250", thumb:"100x100#"}
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end

Categories Controller

class CategoriesController < ApplicationController
  before_action :set_category, only: [:show, :edit, :update, :destroy]

  def index
    @categories = Category.all
  end

  def show
  end

  def new
    @category = Category.new
  end

  def edit
  end

  def create
    @category = Category.new(category_params)

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

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

  def destroy
    @category.destroy
    respond_to do |format|
      format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_category
      @category = Category.find(params[:id])
    end

    def category_params
      params.require(:category).permit(:name, :parent_id)
    end
end

How i Can Ensure the current_user by passing it into Scope So that It gives me only Associated Relation Data

In the Code I have Index Method in the NotificationsController

def index  
@notifications = Notification.role_ids_of_user(current_user).notifications_order_by_desc.page(params[:page])
// If i passed nil in place of current_user there should be some Error Handling How it Will done
end

In The Notification.rb

scope :role_ids_of_user, ->(current_user) { where(:role_id => current_user.pluck(:id),:state => "published") }

I want a Error Handling where we can perform for Current_user authentication

RSpec for a rails controller

I am new to ROR and RSpec. I have written a controller that updates staff for a student like below:

class EStudentsController < ApplicationController def allot @staff= Staff.find(params[:staff_id]) @student= Student.find(@staff.staff_id) @estaffforstudent= EStaffStudent.find(params[:student_id]) @estaffforstudent.staff_id = @staff.id @estaffforstudent.save redirect_to [@student, @staff] end

How do I write RSpec for the above? Some examples with study resources will be helpful.

Thanks for the help.

How to use ESI for fragment caching in Varnish, in Ruby on Rails app built on spree?

The basic syntax is not working for me. I would like not to store user specific information in my cache, but want to cache rest of the page. Please provide syntax to do that in Rails app built on Spree.

accessing iframe elements from rails 3 partial

I am trying to access iframe dom elements from rails 3 partial but its not as expected.

I am trying to access the iframe like this

$j("#batch_grid_frame").contents().find('#ship_box_id').html("HTML")

When i access the page from application it does not update the DOM. But when i run the same below code in browser console this works.

$j("#batch_grid_frame").contents().find('#ship_box_id').html("HTML")

Any help will be appreciated. Thanks.

File deleted each time

I have a ruby controller

def new
    counter = 1
    fileW = File.new("query_output.txt", "w") 
    file = File.new("query_data.txt", "r")
    while (line = file.gets)
        puts "#{counter}: #{line}"
        query = "select name,highway from planet_osm_line where name ilike '" +line+"'"
        @output = PlanetOsmLine.connection.execute(query)   
        @output.each do |output|
            fileW.write(output['highway'] + "\n")
        end
        counter = counter + 1
    end
    file.close
    query = ""
   @output = PlanetOsmLine.connection.execute(query)
 end

So in this I am reading from a file like

    %12th%main%
    %100 feet%
    %12th%main%
    %12th%main%
    %12th%main%
    %100 feet%

In the ruby console I can see all the queries getting executed but in query_output.txt I only get the output of last query. What am I doing wrong here?

lundi 27 juillet 2015

Fetch Data From Multiple Models In One View

This seems easy but I can't figure out how to do it

I'm trying to implement Ransack search in my rails app and for that I have a generated a model Cofounder which don't have any fields in it and I have association between Cofounder and CustomUser model which has email and other fields but i only want to search through email using ransack, i have this association between these two:

has_many :cofounders
belongs_to :CustomUser

(Do i need to have id if Yes how do i do it)

CoFounder Model

class Cofounder < ActiveRecord::Base
    belongs_to :CustomUser  
end

CofoundersController

class CofoundersController < ApplicationController

    layout "custom_layout", only: [:index]

    def index
        @q = Cofounder.ransack(params[:q])
        @cofounders = @q.result
        @cofoundes = CustomUser.all
        @countries = Country.all
    end
end

and in my index view

<% search_form_for @q, url: cofounders_index_path do |f| %>
    <%= f.search_field :email_cont, placeholder: "Search Here" %>
      <%= f.submit "Search" %>
<% end %>

<%= select_tag "search_by_country", options_for_select(@countries.collect{|x| [x.name]} , params[:search_by_country] ),{prompt: "Select country"} %><br><br>

<%= select_tag "choose_a_role", options_for_select(@cofoundes.collect{|x| [x.first_name]} , params[:choose_a_role] ),{prompt: "Choose A Role", id: "select", multiple: true} %><br><br>

 <% @cofoundes.each do |cofounder| %>
   <%= cofounder.email %>
 <%end%>

it is giving me error code

undefined method `email_cont' for #

i know email_cont if not a field in cofounder and i'm accessing that field in cofounder which is giving me error, how do i get those values in cofounder for successful Ransack search.

any help would be appreciated :)

Rails gem to handle comments mentions (e.g.: @user)

I'm developing a Rails app which needs to mention other users in comments, like twitter, using @username. I googled and found socialization gem that has more than I need for now.

Any advices?

Thanks!

Error when installing devise- i am a novice

I have installed rails and am running the Git Bash and am on windows 7 64 bit, i have installed gemfile and updated and this is my first use of ruby! I am following the instrustions from devise's github http://ift.tt/LkuK7q . I am probably being very stupid but when i run gem 'devise' and this error occurs:

ERROR: while executing gem... <Gem::commandlinerror> unknown command /devise

Any help would be greatly appreciated

bundle exec rake assets:precompile fails in Dev Environment

Development.rb: config.assets.debug = false config.assets.compile = true config.assets.enabled = true config.assets.digest = true config.assets.raise_runtime_errors = true

bundle exec rake assets:precompile --trace

` Invoke assets:precompile (first_time)
 ** Invoke assets:environment (first_time)
 ** Execute assets:environment
 ** Invoke environment (first_time)
 ** Execute environment
 ** Execute assets:precompile
 rake aborted! `

ExecJS::ProgramError: TypeError: Object doesn't support this property or method c:/Ruby193/lib/ruby/gems/1.9.1/gems/execjs-`

how to test rails custom validation

I have a custom validation that checks whether a param is valid JSON or not:

 def is_valid_json
    begin
      !!JSON.parse(preferences)
    rescue
      errors.add(:preferences, "This is not valid JSON")
    end
  end

In my controller test, I want to make sure that when I send in a bad value, the status code of the response is 422. Here is the spec from my controller:

  it 'should return a 422 when validations fail' do
    put :update, {:user_preferences => { :email => @email, :preferences => 'badval' } }
    expect(response.status).to eq(422)
    res = JSON.parse(response.body)
    expect(res['error']).to_not be_blank
  end

The test fails due to an error:

Failure/Error: put :update, {:user_preferences => { :email => @email, :preferences => 'badval' } }
ActiveRecord::RecordInvalid:
Validation failed: Preferences This is not valid JSON

Controller code:

 def update
    @user_preference = UserPreference.where(email: params[:user_preferences][:email]).first
    authorize! :update, @user_preference
    @user_preference.update_attributes!(params[:user_preferences])
    render_api_response(@user_preference)
  end

When I make the request from the browser, I get a 422 return status code, so is there a reason that I can't get the same result from the test?

Rails delete table row via migration

I'm trying to delete several rows in the table actionable_items via the following migration. I have debugged and can confirm that the variables that store the table row are not nil. The migration runs successfully, but it doesn't delete the row from the table. Also, does anyone know why I can debug a migration when I run rake db:migrate:redo but not when I run rake db:migrate ?

class RemoveActionableItems < ActiveRecord::Migration
  class ActionableItem < ActiveRecord::Base
    attr_accessible :actionable_item, :name, :sequence, :type
  end

  class MenuItemTEMP < ActionableItem
    self.table_name = "actionable_items"
  end

  class InsightReportMenuItemTEMP < ActionableItem
    self.table_name = "actionable_items"
  end

  def up
    validation_settings = MenuItem.find_by_name("Validation Settings")
    identifier_lookup = MenuItem.find_by_name("Identifier Lookup")
    compliance = InsightReportMenuItem.find_by_name("Compliance")
    debugger
    validation_settings.destroy! #unless validation_settings.nil?
    identifier_lookup.destroy! #unless identifier_lookup.nil?
    compliance.destroy! #unless compliance.nil?
  end

  def down
    MenuItem.create :name => "Validation Settings", :type => "MenuItem"
    MenuItem.create :name => "Identifier Lookup", :type => "MenuItem"
    InsightReportMenuItem.create :name => "Compliance", :type => "InsightReportMenuItem"
  end
end

I also tried deleting from the rails console, but once again, pgAdmin is showing the row not deleted.

pmpaware-webapp(development)> compliance = InsightReportMenuItem.find_by_name("Compliance")
  InsightReportMenuItem Load (3.8ms)  SELECT "actionable_items".* FROM "actionable_items" WHERE "actionable_items"."type" IN ('InsightReportMenuItem') AND "actionable_items"."name" = 'Compliance' LIMIT 1
=> #<InsightReportMenuItem id: 264, name: "Compliance", actionable_item_id: nil, created_at: "2015-07-23 18:57:25", updated_at: "2015-07-23 18:57:25", actionable_items_count: 0, sequence: nil, type: "InsightReportMenuItem">
pmpaware-webapp(development)> compliance.errors
=> #<ActiveModel::Errors:0x007fc0735ac540 @base=#<InsightReportMenuItem id: 264, name: "Compliance", actionable_item_id: nil, created_at: "2015-07-23 18:57:25", updated_at: "2015-07-23 18:57:25", actionable_items_count: 0, sequence: nil, type: "InsightReportMenuItem">, @messages={}>
pmpaware-webapp(development)> compliance.delete

  SQL (111829.8ms)  DELETE FROM "actionable_items" WHERE "actionable_items"."type" IN ('InsightReportMenuItem') AND "actionable_items"."id" = 264
=> #<InsightReportMenuItem id: 264, name: "Compliance", actionable_item_id: nil, created_at: "2015-07-23 18:57:25", updated_at: "2015-07-23 18:57:25", actionable_items_count: 0, sequence: nil, type: "InsightReportMenuItem">

cannot get /admin for Activeadmin

I have an existing app with Rails 3.2.17 and angular js. I would like to include Activeadmin in the existing app.

I followed the steps from active-admin post from ryan bates. I performed following processes:

  1. Added gem activeadmin in Gemfile
  2. Run bundle install
  3. rails g active_admin:install --skip-users (as I already have devise)

I have following routes if I run rake routes:

          admin_root             /admin(.:format)                                                           admin/dashboard#index
          admin_dashboard GET    /admin/dashboard

Then I restart my rails server and go to localhost:3000/admin. I have an error that says cannot get /admin. Can anyone please let me know if I am missing anything?

Active Record Association: why does @owner.@target.count yield a result of 1 when @owner.@target returns an empty array?

I have models in my Rails app:

Sales_Opportunity which has_many Swots.

I'm setting them up using FactoryGirl and running a test to show that when I delete my Sales_Opportunity I also cause the associated Swots to be deleted. For some reason when debugging with Byebug I'm getting strange results - the Sales_Opportunity and Swot records are being correctly created, but when I run sales_opportunity.swots it returns [ ] whereas sales_opportunity.swots.count returns 1. What's more odd is the exact same code works fine with anther object association (timeline_events are exactly like swots yet work perfectly with the same code).

Can anyone tell me what am I doing wrong please?

Sales_Opportunity.rb:

class SalesOpportunity < ActiveRecord::Base
 default_scope { order('close_date ASC') }
 belongs_to :user
 belongs_to :company
 has_many :key_contacts
 has_many :timeline_events, dependent: :destroy
 has_many :swots, dependent: :destroy
end

Swot.rb:

class Swot < ActiveRecord::Base
 belongs_to :sales_opportunity
 validates :swot_details, presence: true
 validates :sales_opportunity_id, presence: true
 enum swot_type: [:strength, :weakness, :opportunity, :threat]
 enum swot_importance: { minimal: 1, marginal: 2, noteworthy: 3, significant: 4, critical: 5 }
 validates :swot_importance, presence: true
end

Swot FactoryGirl spec:

FactoryGirl.define do
factory :swot do
    swot_importance             "minimal"
    swot_details                "Some boring details"
    swot_type                   "threat"

    trait :attached do
        association             :sales_opportunity, :with_user_id
    end
 end
end

Sales_Opportunity FactoryGirl spec:

FactoryGirl.define do
sequence(:opportunity_name) { |n| "Sales Oppotunity - #{n}" }

factory :sales_opportunity do
    user
    opportunity_name {generate(:opportunity_name)}
    close_date                  "2014/12/12"
    sale_value                  10000
    company_id                  7

    trait :with_user_id do
        user_id                     6
    end
end
end

Failing Rspec tests:

describe "when swot's parent sales opportunity is destroyed" do
    let(:swot) { FactoryGirl.create(:swot, :attached) }
    let(:sales_opportunity) { swot.sales_opportunity }

it "should destroy associated swots" do
    dswots = sales_opportunity.swots.to_a
    byebug
    sales_opportunity.destroy
    expect(dswots).not_to be_empty
    dswots.each do |dswot|
    expect(Swot.where(id: dswot.id)).to be_empty
  end
end
  end

Output from the console (byebug) when logging swot:

#<Swot id: 13, swot_type: 3, swot_importance: 1, sales_opportunity_id: 564, swot_details: "Some boring details", created_at: "2015-07-27 10:57:23", updated_at: "2015-07-27 10:57:23">

Output from the console when logging sales_opportunity:

#<SalesOpportunity id: 564, close_date: "2014-12-12 00:00:00", user_id: 6, created_at: "2015-07-27 10:57:23", updated_at: "2015-07-27 10:57:23", pipeline_status: 0, opportunity_name: "Sales Oppotunity - 4", company_id: 7, sale_value: #<BigDecimal:7fe9ffd25078,'0.1E5',9(27)>, swot_score: 0>

Output for sales_opportunity.swots.count:

(byebug) sales_opportunity.swots.count
 1

Output for sales_opportunity.swots:

(byebug) sales_opportunity.swots
#<ActiveRecord::Associations::CollectionProxy []>

I think I've included all the known info. The Rspec tests, FactoryGirl factories and setup between sales_opportunities and Swots/Timeline_Events is exactly the same - yet the Rspec tests pass for Timeline_Events and the collection_proxy works for those (so as far as I can tell, the code is identical):

Timeline_Event Factory:

FactoryGirl.define do
factory :timeline_event do
    activity                    "Some activity"
    due_date                    "2014/11/11"

    trait :attached do
        association             :sales_opportunity, :with_user_id
    end
end
end

Working Rspec tests:

describe "when sales opportunity is destroyed for timeline event" do
    let(:timeline_event) { FactoryGirl.create(:timeline_event, :attached) }
    let(:sales_opportunity) { timeline_event.sales_opportunity }

it "should destroy associated timeline events" do
    timeline_events = sales_opportunity.timeline_events.to_a
    sales_opportunity.destroy
    expect(timeline_events).not_to be_empty
    timeline_events.each do |event|
    expect(TimelineEvent.where(id: event.id)).to be_empty
  end
end
end

Timeline_Event.rb:

class TimelineEvent < ActiveRecord::Base
 belongs_to :sales_opportunity
 validates :activity, presence: true 
 validates :due_date, presence: true
 validates :sales_opportunity_id, presence: true
end

When running byebug in the same place here I get an array including the Timeline_Event.

Can anyone help me understand what's going wrong in my code?

Thanks.

dimanche 26 juillet 2015

Access denied for user 'root'@'localhost' (using password: YES) (Mysql2::Error)

Want to consult on the below error message:

Ruby (Rack) application could not be started

These are the possible causes:

There may be a syntax error in the application's code. Please check for such errors and fix them.

A required library may not installed. Please install all libraries that this application requires.

The application may not be properly configured. Please check whether all configuration files are written correctly, fix any incorrect configurations, and restart this application.

A service that the application relies on (such as the database server or the Ferret search engine server) may not have been started. Please start that service.

Further information about the error may have been written to the application's log file. Please check it in order to analyse the problem.

Error message:

Access denied for user 'root'@'localhost' (using password: YES) (Mysql2::Error) Exception class: PhusionPassenger::UnknownError Application root: /usr/local/sipfish/webui Backtrace:

File Line Location

0 /usr/lib64/ruby/gems/1.9.1/gems/mysql2-0.3.11/lib/mysql2/client.rb 44 in connect' 1 /usr/lib64/ruby/gems/1.9.1/gems/mysql2-0.3.11/lib/mysql2/client.rb 44 ininitialize' 2 /usr/lib64/ruby/gems/1.9.1/gems/activerecord-3.1.12/lib/active_record/connection_adapters/mysql2_adapter.rb 17 in new' 3 /usr/lib64/ruby/gems/1.9.1/gems/activerecord-3.1.12/lib/active_record/connection_adapters/mysql2_adapter.rb 17 inmysql2_connection' 4 /usr/lib64/ruby/gems/1.9.1/gems/activerecord-3.1.12/lib/active_record/connection_adapters/abstract/connection_pool.rb 304 in new_connection' 5 /usr/lib64/ruby/gems/1.9.1/gems/activerecord-3.1.12/lib/active_record/connection_adapters/abstract/connection_pool.rb 323 incheckout_new_connection' 6 /usr/lib64/ruby/gems/1.9.1/gems/activerecord-3.1.12/lib/active_record/connection_adapters/abstract/connection_pool.rb 265 in block (2 levels) in checkout' 7 /usr/lib64/ruby/gems/1.9.1/gems/activerecord-3.1.12/lib/active_record/connection_adapters/abstract/connection_pool.rb 261 inloop' 8 /usr/lib64/ruby/gems/1.9.1/gems/activerecord-3.1.12/lib/active_record/connection_adapters/abstract/connection_pool.rb 261 in block in checkout' 9 /usr/lib64/ruby/1.9.1/monitor.rb 211 inmon_synchronize' 10 /usr/lib64/ruby/gems/1.9.1/gems/activerecord-3.1.12/lib/active_record/connection_adapters/abstract/connection_pool.rb 260 in checkout' 11 /usr/lib64/ruby/gems/1.9.1/gems/activerecord-3.1.12/lib/active_record/connection_adapters/abstract/connection_pool.rb 162 inconnection' 12 /usr/lib64/ruby/gems/1.9.1/gems/activerecord-3.1.12/lib/active_record/connection_adapters/abstract/connection_pool.rb 409 in retrieve_connection' 13 /usr/lib64/ruby/gems/1.9.1/gems/activerecord-3.1.12/lib/active_record/connection_adapters/abstract/connection_specification.rb 115 inretrieve_connection' 14 /usr/lib64/ruby/gems/1.9.1/gems/activerecord-3.1.12/lib/active_record/connection_adapters/abstract/connection_specification.rb 89 in connection' 15 /usr/local/sipfish/webui/config/initializers/verify_voip_phone_parity.rb 1 in' 16 /usr/lib64/ruby/gems/1.9.1/gems/activesupport-3.1.12/lib/active_support/dependencies.rb 234 in load' 17 /usr/lib64/ruby/gems/1.9.1/gems/activesupport-3.1.12/lib/active_support/dependencies.rb 234 inblock in load' 18 /usr/lib64/ruby/gems/1.9.1/gems/activesupport-3.1.12/lib/active_support/dependencies.rb 225 in load_dependency' 19 /usr/lib64/ruby/gems/1.9.1/gems/activesupport-3.1.12/lib/active_support/dependencies.rb 234 inload' 20 /usr/lib64/ruby/gems/1.9.1/gems/railties-3.1.12/lib/rails/engine.rb 556 in block (2 levels) in ' 21 /usr/lib64/ruby/gems/1.9.1/gems/railties-3.1.12/lib/rails/engine.rb 555 ineach' 22 /usr/lib64/ruby/gems/1.9.1/gems/railties-3.1.12/lib/rails/engine.rb 555 in block in ' 23 /usr/lib64/ruby/gems/1.9.1/gems/railties-3.1.12/lib/rails/initializable.rb 30 ininstance_exec' 24 /usr/lib64/ruby/gems/1.9.1/gems/railties-3.1.12/lib/rails/initializable.rb 30 in run' 25 /usr/lib64/ruby/gems/1.9.1/gems/railties-3.1.12/lib/rails/initializable.rb 55 inblock in run_initializers' 26 /usr/lib64/ruby/gems/1.9.1/gems/railties-3.1.12/lib/rails/initializable.rb 54 in each' 27 /usr/lib64/ruby/gems/1.9.1/gems/railties-3.1.12/lib/rails/initializable.rb 54 inrun_initializers' 28 /usr/lib64/ruby/gems/1.9.1/gems/railties-3.1.12/lib/rails/application.rb 96 in initialize!' 29 /usr/lib64/ruby/gems/1.9.1/gems/railties-3.1.12/lib/rails/railtie/configurable.rb 30 inmethod_missing' 30 /usr/local/sipfish/webui/config/environment.rb 5 in ' 31 config.ru 3 inrequire' 32 config.ru 3 in block in ' 33 /usr/lib64/ruby/gems/1.9.1/gems/rack-1.3.10/lib/rack/builder.rb 51 ininstance_eval' 34 /usr/lib64/ruby/gems/1.9.1/gems/rack-1.3.10/lib/rack/builder.rb 51 in initialize' 35 config.ru 1 innew' 36 config.ru 1 in ' 37 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/rack/application_spawner.rb 225 ineval' 38 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/rack/application_spawner.rb 225 in load_rack_app' 39 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/rack/application_spawner.rb 157 inblock in initialize_server' 40 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/utils.rb 572 in report_app_init_status' 41 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/rack/application_spawner.rb 154 ininitialize_server' 42 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/abstract_server.rb 204 in start_synchronously' 43 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/abstract_server.rb 180 instart' 44 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/rack/application_spawner.rb 129 in start' 45 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/spawn_manager.rb 253 inblock (2 levels) in spawn_rack_application' 46 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/abstract_server_collection.rb 132 in lookup_or_add' 47 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/spawn_manager.rb 246 inblock in spawn_rack_application' 48 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/abstract_server_collection.rb 82 in block in synchronize' 49 prelude> 10:insynchronize' 50 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/abstract_server_collection.rb 79 in synchronize' 51 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/spawn_manager.rb 244 inspawn_rack_application' 52 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/spawn_manager.rb 137 in spawn_application' 53 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/spawn_manager.rb 275 inhandle_spawn_application' 54 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/abstract_server.rb 357 in server_main_loop' 55 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11/lib/phusion_passenger/abstract_server.rb 206 instart_synchronously' 56 /usr/lib64/ruby/gems/1.9.1/gems/passenger-3.0.11//helper-scripts/passenger-spawn-server 99 in ` '

Stop file write if file size exceeds 500KB ruby on rails

How can I stop file writing ( upload form remote url ) when file size exceeds 500KB ?

I am using following code to upload a remote file

require 'open-uri'
open('temp/demo.doc', 'wb') do |file|
  file << open('http://ift.tt/1LJxj3W').read
end

this code is working properly and I am able to get files in temp folder. Now I want if filesize exceeds 500KB then it should stop writing file. In other words I want only 500KB of file if it is more than 500KB

Check form submitted values in ruby on rails

On my rails app I have a form on /addfiles where user can add file path in text boxes and this form is submitted to /remotefiles

I have created a route match '/remotefiles' => 'main#remotefiles'

and function in main controller

def remotefiles
    render layout: false
end

and add remotefiles.html.haml in views/main

how can I show these submitted values on remotefiles, I think it can be done with render but not sure how can I use it to pass form values and show them on view.

Is there a way to check form data in ruby on rails just like php print_r function ?

How to dynamically load data in Rails 4

So i have this page that has the functionality of creating a new course and listing all courses on the same page.

What i want,is when i click on the id of the courses to dynamically load all lessons associated with that id ion a div below that.

this is the index.html.erb of courses

<% provide(:title, 'All courses') %>
<h1>All Courses </h1>
<p><%= link_to "Back", admin_path, class: "btn-submit" %></p>

<div class="text-center">
  <%= form_for [:admin, @course] do |f|%>
  <%= render 'shared/error_messages', object: f.object %>
  <p>
    Create a new course
  </p>

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

    <%= f.label :description%>
    <%= f.text_area(:description, size: "24x2") %>

    <%= f.label :duration%>
    <%= f.number_field(:duration, step: 0.5) %>

    <%= f.label :category%>
    <%= f.text_field(:category) %>

    <%= f.label :tag%>
    <%= f.text_field(:tag) %>


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

<table class="display responsive no-wrap text-center" id="datatableadmin">
  <thead>
    <tr>
      <th>id</th>
      <th>Title</th>
      <th>Description</th>
      <th>Duration</th>
      <th>Category</th>
      <th>Tag</th>
      <th>Deletion</th>
    </tr>
  </thead>
  <tbody>
    <% @courses.each do |c| %>
      <tr>
        <td><%= c.id %></td>
        <td><%= best_in_place c, :title, url: "courses/#{c.id}", cancel_button: 'X' %></td>
        <td><%= best_in_place c, :description, url: "courses/#{c.id}" %></td>
        <td><%= best_in_place c, :duration, url: "courses/#{c.id}" %></td>
        <td><%= best_in_place c, :category, url: "courses/#{c.id}" %></td>
        <td><%= best_in_place c, :tag, url: "courses/#{c.id}" %></td>
        <td><%= link_to "Remove", admin_course_path(c), method: :delete, data: { confirm: "Are you sure?" }%></td>
      </tr>
    <% end %>
  </tbody>
</table>
<div class="text-center">
  <small style="color:red;">Edit by clicking the fields and pressing enter. Cancel by clicking the X button</small>
</div>

so basically if you look down where it says c.id, i want the functionality to call all lessons associated with that id when clicking on that id.

Rails create profile after sign up in devise

i have installed devise in my app and now i want to create profile just after the individual(user) signed up and redirect them to the profile page

here is my individual model

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

my profile model is

class Profile < ActiveRecord::Base
  belongs_to :individual
  before_create :build_profile
end

Migration file for profile is

class CreateProfiles < ActiveRecord::Migration
  def change
    create_table :profiles do |t|
      t.belongs_to :individual, index: true
      t.string :first_name
      t.string :last_name
      t.string :age
      t.string :birth_date
      t.string :gender
      t.string :bio
      t.string :linkedin_profile
      t.string :facebook_profile
      t.string :twitter_profile
      t.integer :mobile_no

      t.timestamps null: false
    end
  end
end

and my profiles controller is given as

class ProfilesController < ApplicationController
    before_action :authenticate_individual!
    before_action :find_profile, only: [:show, :edit, :update, :destroy]

    respond_to :html

    def index
      @profiles = Profile.all
    end

    def new
      @profile = current_individual.build_profile
    end

    def create
      @profile = current_individual.build_profile(profile_params)
      if @profile.save
        flash[:success] = "Profile saved"
        redirect_to current_individual_path
      else
        flash[:error] = "Error"
        render :new
      end
    end

    def show
      @profile = Profile.find(params[:id])
    end

    def edit
    end

    def update
      @profile.update(profile_params)
      respond_with(@profile)
    end


    private

    def find_profile
      @profile = Profile.find(params[:id])
    end

    def profile_params
      params.require(:profile).permit(:first_name, :last_name, :birth_date,
                                      :gender, :bio, :personal_website, :linkedin_profile, :facebook_profile,
                                      :mobile_no, :telephone_no)
    end
  end

and i have the routes as

devise_for :individuals

please tell me how can the user will be signed up and after signing in they would be redirected to profile's edit view where the individual can edit the profile Thank you !!

samedi 25 juillet 2015

How to organize form_for helper to show data from different models?

I have three models PriceGroup, PriceGroupLine and Item. PriceGroup has fields - :id and :name. Item has fields - :id and :name. PriceGroupLine has fields - :id, :price_group_id, :item_id, :price

Associations:

PriceGroup has_many PriceGroupLines

Item has_one PriceGroupLine

PriceGroupLine belongs_to Item

PriceGroupLine belongs_to PriceGroup

I need to insert in PriceGroupLine model lines from PriceGroup show view. How I should organize form_for helper if I need to insert in PriceGroupLine:

item_id - items list organized with collection_select helper
price_group_id
price of item

And one more question about the associations. At the beginning i had associations like:

PriceGroup has_many PriceGroupLines

PriceGroupLine has_many Items

Item belongs_to PriceGroupLine

PriceGroupLine belongs_to PriceGroup

But this associations didn't work correctly when i tried to get :name field from Item model like this:

<% @price_group.price_group_lines.each do |price_group_line| %>
  <%= price_group_line.item.try(:name) %>>
  <%= price_group_line.price %>
<% end %>

I changed associations and all worked. Now PriceGroupLine belongs_to :item and Item has_one :price_group_line. But it is logical to assume that ITEM is belongs to PriceGroupLine (PRICEGROUPLINE contains ITEM). Am I wrong?

rails_admin dropdown select in edit

I'm using Rails Admin to manage my website.

Question 1: In Edit, I've got some has many relations fields. When I'm typing something in the dropdown select, for example "eau" (water in french), I've got a big list of ingredients that contain the letters "eau", or an other exemple, for "farine" (flour in french), I've got many type of "farine" but only the word "farine" is all the time at the end. I think it's because "farine" or "eau" are created before the other...

Is there a way to change the order and displaying "farine" or "eau" in first?

Question 2: On the same field, is that possible to search with case insensitive, actually, I would like to search a word without taking accents into account.

Hope someone can help me for this :)

Ruby on Rails: Why doesn't my delete link work?

I am following the Rails guide: http://ift.tt/IsdtVd

and I have the following line in my index.html.erb:

 <%= link_to 'Destroy', team_path(team), method: :delete, data: { confirm: 'Are you sure?' } %>

But it doesn't work; it just goes to the show page.

For your information, this is my routes.rb:

Rails.application.routes.draw do

  get 'bets/index'
  root 'bets#index'
  resources :teams
end

My controller:

def destroy
    @team = Team.find(params[:id])
    @team.destroy
    redirect_to teams_path
end

My application.js:

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree
//= require jquery
//= require jquery_ujs .

My application.html.erb:

<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'defaults', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>

Please note that I have tried changing <%= javascript_include_tag 'defaults', 'data-turbolinks-track' => true %> to <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>, but this gives me the following error:

 Showing C:/Sites/BettingSite/app/views/layouts/application.html.erb where line #6 raised:

TypeError: Object doesn't support this property or method
(in C:/Sites/BettingSite/vendor/cache/ruby/2.1.0/gems/turbolinks-2.5.3/lib/assets/javascripts/turbolinks.js.coffee)

Line 6 is the line: <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>

Can someone please help me?

Rails: Multi-Step New User Signup Form (First argument in form cannot contain nil or be empty)

I'm a beginner and have a serious problem with making two steps signing up.

I keep getting that error:

First argument in form cannot contain nil or be empty
<%= form_for(@Profile) do |f| %>

Users can sign up with their user information which are on the user table(DB). And all is fine with them. But I really want them to have profiles. So they can put their bio for example.

I tried to create MVC structure for the profiles based on users' MVC but it doesn't work.

I have been trying to find the answer for days. Tried hundreds of variations but nothing worked out. Please help!

views/users/new.html.erb (This is working)( I just wanted to create profile for the users and give them the ability to fill out their information as the second steps of the signing up)

<div class="container">
  <% provide(:title, 'Sign up') %>
  <h1 class="center">Sign up</h1>

  <div class="row">
    <div class="col s12 m10 l8 offset-m1 offset-l2">
      <%= form_for(@user) do |f| %>
        <%= render 'shared/error_messages', object: f.object %>

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

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

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

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

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

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

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

        <%= f.label :password_confirmation, "Confirmation" %>
        <%= f.password_field :password_confirmation %>
        <div class="row center">
        <%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
        </div>
      <% end %>
    </div>
  </div>
</div>

models/user.rb

class User < ActiveRecord::Base
  has_one  :profile
  has_many :microposts, dependent: :destroy
  has_many :relationships, foreign_key: "follower_id", dependent: :destroy
  has_many :followed_users, through: :relationships, source: :followed
  has_many :reverse_relationships, foreign_key: "followed_id",
                                   class_name:  "Relationship",
                                   dependent:   :destroy
  has_many :followers, through: :reverse_relationships, source: :follower
  before_save { self.email = email.downcase }
  before_create :create_remember_token
  validates :first_name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
  validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, length: { minimum: 6 }

  def User.new_remember_token
    SecureRandom.urlsafe_base64
  end

  def User.digest(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  def feed
    Micropost.from_users_followed_by(self)
  end

  def following?(other_user)
    relationships.find_by(followed_id: other_user.id)
  end

  def follow!(other_user)
    relationships.create!(followed_id: other_user.id)
  end

  def unfollow!(other_user)
    relationships.find_by(followed_id: other_user.id).destroy
  end

  private

    def create_remember_token
      self.remember_token = User.digest(User.new_remember_token)
    end
end

controllers/users_controller.rb

    class UsersController < ApplicationController


    before_action :signed_in_user,
                    only: [:index, :edit, :update, :destroy, :following, :followers]
      before_action :correct_user,   only: [:edit, :update]
      before_action :admin_user,     only: :destroy

      def index
        @users = User.paginate(page: params[:page])
      end

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

      def new
        @user = User.new
      end



  def create
    @user = User.new(user_params)
    if @user.save
      sign_in @user
      flash[:success] = "Welcome to the my app"
      redirect_to @user
    else
      render 'new'
    end
  end

  def edit
  end

  def update
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated"
      redirect_to @user
    else
      render 'edit'
    end
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "just got destroyed."
    redirect_to users_url
  end

  def following
    @title = "Connections"
    @user = User.find(params[:id])
    @users = @user.followed_users.paginate(page: params[:page])
    render 'show_follow'
  end

  def followers
    @title = "known by"
    @user = User.find(params[:id])
    @users = @user.followers.paginate(page: params[:page])
    render 'show_follow'
  end

  private

    def user_params
      params.require(:user).permit(:first_name, :middle_name, :last_name, :preferred_name, :email, :password,
                                   :password_confirmation)
    end

    # Before filters

    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_url) unless current_user?(@user)
    end

    def admin_user
      redirect_to(root_url) unless current_user.admin?
    end
  end

second signup page
views/users/signup2.html.erb

<div class="container">
  <% provide(:title, 'Sign up2') %>
  <h1 class="center">Sign up2</h1>

  <div class="row">
    <div class="col s12 m10 l8 offset-m1 offset-l2">
      <%= form_for(@Profile) do |f| %>
        <%= render 'shared/error_messages', object: f.object %>

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

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

        <div class="row center">
        <%= f.submit "Create my account2", class: "btn btn-large btn-primary" %>
        </div>
      <% end %>
    </div>
  </div>
</div>

models/profile.rb

class Profile < ActiveRecord::Base
  belongs_to :user
end

controllers/profiles_controller.rb

class ProfilesController < ApplicationController

  before_filter :get_user

  def get_user
    @profile = User.find(params[:user_id])
  end

  # generate new-profile form
  def new
    @user.profile = Profile.new
    @profile = @user.profile
  end

  # process new-profile-form post
  def create

    @user.profile = Profile.new(params[:profile])
    @profile = @user.profile

    respond_to do |format|
      if @profile.save
        flash[:notice] = 'Profile was successfully created.'
        format.html { redirect_to(@profile) }
        format.xml  { render :xml => @profile, :status => :created, :location => @profile }
      ...
      end
    end

  end

  # generate edit-profile form
  def edit
    @profile = Profile.find(params[:id])
  end

  # generate edit-profile-form post
  def update

    @profile = @user.profile

    respond_to do |format|
      if @profile.update_attributes(params[:profile])
        flash[:notice] = 'Profile was successfully updated.'
        # format.html { redirect_to(@profile) }
        format.html { redirect_to(user_profile(@user)) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @profile.errors, :status => :unprocessable_entity }
      end
    end

end

Routes.rb

 root to: 'static_pages#home'
  match '/signup',  to: 'users#new',            via: 'get'
  match '/signup2', to: 'profiles#new',         via: 'get'
  match '/signin',  to: 'sessions#new',         via: 'get'
  match '/signout', to: 'sessions#destroy',     via: 'delete'
  match '/help',    to: 'static_pages#help',    via: 'get'
  match '/about',   to: 'static_pages#about',   via: 'get'
  match '/contact', to: 'static_pages#contact', via: 'get'
end

Ruby on rails Databases with large volumes of data effect speed?

My question is pretty much in the title but I'm wondering if a large quantity of data with largely effect the speed of a database in ruby on rails in my current case I want to store every users games in one database with a id that references to the user however I feel that if I do this eventually that database will get too big and slow the whole website down so will it not matter or would there be a better way of doing something like this?

Thanks in advance

-Jason Attwood