mardi 30 juin 2015

HTML to Word convertion in Rails

Rails version: 3.2 Ruby version: 1.9.3

In my Rails app, there is an HTML file which I would like to convert to a WORD format without loosing its structure / design. I have used htmltoword gem. But the HTML is not rendered exactly alike in to the Word file. It has got design issues. It is not interpreting tables, ul li etc correctly.

So, I would like to have better suggestions for implementing this feature. Thank you.

Rails "includes" Method and Avoiding N+1 Query

I don't understand the Rails includes method as well as I'd like, and I ran into an issue that I'm hoping to clarify. I have a Board model that has_many :members and has_many :lists (and a list has_many :cards). In the following boards controller, the show method looks as follows:

def show
  @board = Board.includes(:members, lists: :cards).find(params[:id])
  ...
end

Why is the includes method needed here? Why couldn't we just use @board = Board.find(params[:id]) and then access the members and lists via @board.members and @board.lists? I guess I'm not really seeing why we would need to prefetch. It'd be awesome if someone could detail why this is more effective in terms of SQL queries. Thanks!

Editor not loading up sometimes

It just shows this with a tiny box:

<p><u><em><strong>Synopsis</strong></em></u></p>

<p><u><em><strong>

I suspect the page is slow and it just doesn't load. What do I do? When I say ckeditor doesn't load, I mean it doesn't provide any styles or edits or anything. It just shows a tiny box. I'll show it below. Any help would be appreciated

application.js

//= require ckeditor/init
//= require_self
//= require jquery
//= require jquery_ujs
//= require chosen-jquery
//= require turbolinks
//= require_tree .
//= require bootstrap-sprockets

ckeditor/config.js

  CKEDITOR.editorConfig = function( config )
  {
  /* Filebrowser routes */
  // The location of an external file browser, that should be launched when "Browse Server" button is pressed.


  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.


  // The location of a script that handles file uploads in the Flash dialog.
  config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.


  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.


  // The location of a script that handles file uploads in the Image dialog.
  config.filebrowserImageUploadUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads.
  config.filebrowserUploadUrl = "/ckeditor/attachment_files";

  // Rails CSRF token
  config.filebrowserParams = function(){
    var csrf_token, csrf_param, meta,
        metas = document.getElementsByTagName('meta'),
        params = new Object();

    for ( var i = 0 ; i < metas.length ; i++ ){
      meta = metas[i];

      switch(meta.name) {
        case "csrf-token":
          csrf_token = meta.content;
          break;
        case "csrf-param":
          csrf_param = meta.content;
          break;
        default:
          continue;
      }
    }

    if (csrf_param !== undefined && csrf_token !== undefined) {
      params[csrf_param] = csrf_token;
    }

    return params;
  };

  config.addQueryString = function( url, params ){
    var queryString = [];

    if ( !params ) {
      return url;
    } else {
      for ( var i in params )
        queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
    }

    return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
  };

  // Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    var content, upload;

    if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
      content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
      upload = (content == null ? null : content.get('upload'));

      if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
        upload.filebrowser['params'] = config.filebrowserParams();
        upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
      }
    }
  });

  config.toolbar =
    [
        [ 'Undo','Redo'],
        [ 'FontSize', 'Blockquote','-', '-', 'Bold', 'Italic', 'Underline', 'Subscript', 'Superscript', '-', 'RemoveFormat' ],
        [ 'NumberedList', 'BulletedList', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
        ['TextColor','BGColor', 'Maximize'],
        ['Image','Link','Unlink'],
        ['Find']
    ];

    config.enterMode = CKEDITOR.ENTER_P; // inserts <br />;
    config.language = 'en';

  config.htmlEncodeOutput = false;
  config.entities = false;

};

(function() {
  var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
  if (isChrome) {
    CKEDITOR.on( 'instanceLoaded', function( e ){
      this.addCss('.cke_editable { line-height: normal; }');
    });
  }
})();

Rails Mongoid how to get count of tasks for all users of a team?

I have the following schema in mongoid:

Team has many users.

User belongs to team and has many tasks.

Task belongs to user. 

I want to get ALL tasks for a certain team. How can I do it in a single access to DB?

The following query takes too much time:

team = Team.where(_id: params[:id]).first
tasks = 0
team.users.each{|user| tasks = tasks + user.tasks.count}

I would like to do a single access to DB. something like:

team.users.tasks.count

Trying to update Rack gem to 1.5.4 for Rails 3.2 applications

Due to the Denial of Service vulnerability with the Rack gem, I am trying to update the Rack gem from version 1.4.5 to 1.5.4 but receive the below

Bundler could not find compatible versions for gem "rack":
In Gemfile:
rails (= 3.2.22) ruby depends on
  railties (= 3.2.22) ruby depends on
    actionpack (= 3.2.22) ruby depends on
      rack (~> 1.4.5) ruby
rack (~> 1.5.4) ruby

I am not sure what my options are for how to go about updating the rack gem to version 1.5.4 for Rails 3 applications. Should I be able to update the Rack gem to 1.5.4 for Rails 3 applications without any issues?

The way I went about updating the Rack gem within a Rails 3.2 application is: a) Deleted my Gemfile.lock, b) emptied application's gemset, b) Added within the application's Gemfile: gem 'rack', '~> 1.5.4', c) ran "bundle install"

Why debug won't work in this situation?

I'm using the gem called omniauth-facebook, with which I succeeded at implementing of facebook login auth.
It looks fine but it won't pass data of whole object to the view.
It should show array things in the case when using 'debug'

But it shows this somehow :(

--- 
...

Why it won't work as usual? How can I fix it?
I just want to check inside of data as usual.

Controller

@auth = request.env["omniauth.auth"]

View

<%= debug @auth %>

ruby on rails - 1 error prohibited this listing from being saved: Image has contents that are not what they are reported to be

1 error prohibited this listing from being saved: Image has contents that are not what they are reported to be

That's the error that I get when I try to upload a picture for a listing. I've tried various types of validations and nothing is working.

This is what my Model looks like.

class Listing < ActiveRecord::Base
    has_attached_file :image, :styles => { :medium => "200x", :thumb =>"100x100>" }, :default_url => "default.jpg"
    validates_attachment :image, content_type: { content_type: /\Aimage\/.*\Z/ }
end

Can someone please explain to me what I did wrong, and what I can do to fix it. I really want to keep working on this application but I've hit a problem!

Best alternative for Bj plugin for rails 4?

I am upgrading Rails 2 application to Rails 4. I have successfully upgraded in rails 3. Now in Rails 4 Bj plugin is not supported. In my application on some pages Bj help to generate pdf on page load and some other pages Bj generate PDF when click on a button.

I already tried to convert Bj plugin as library for rails 4 but it not help me out.

Can any one give me solution what's the better alternative of Bj or how to upgrade BJ for Rails 4.

Thanks,

Can't Edit Item Error NoMethodError in Items#edit

I have an Item Model. Its for a retail store.

When im on an item view. Lets say for item id 11. Then i click on edit button. I receive the following error

Anyone have any clues? Any help would be greatly appreciated.

NoMethodError in Items#edit
undefined method `errors' for nil:NilClas
<% if @user.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-danger">
      The form contains <%= pluralize(@user.errors.count, "error") %>.
    </div>
    <ul>

Below is where my edit button is in Item View

<!-- right column -->
  <div class="col-lg-6 col-md-6 col-sm-5">
      <div class = "itemtitle"><%= @item.title %> </div> 
      <div class = "price">$<%= @item.price %> </div> 
      <%= link_to "Edit Items", edit_item_path(@item) %>
      <div class="productFilter productFilterLook2">
          <div class="filterBox">
              <select>
                  <option value="strawberries" selected>Quantity</option>
              </select>
          </div>

Here is my Items controller.

class ItemsController < ApplicationController

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

  def new
    @item = Item.new
  end

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

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

  def update
    if @item.update(pin_params)
      redirect_to @item, notice: 'Item was successfully updated.'
    else
      render action: '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.destroy
    respond_to do |format|
      format.html { redirect_to items_url, notice: 'Item was successfully deleted' }
      format.json { head :no_content }
    end
  end

  private

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

end

Rails has_many through: (many to many relationship) error uninitialized constant Group::Keywords

A Group can have many keywords and a Keyword can have many groups. I have this relationship defined as

class Keyword < ActiveRecord::Base
   has_many :groups_keywords
   has_many :groups, through: :groups_keywords
end

class GroupsKeyword < ActiveRecord::Base
  belongs_to :groups
  belongs_to :keywords
end

class Group < ActiveRecord::Base
  has_many :groups_keywords
  has_many :keywords, through: :groups_keywords
end

I can do Group.find(1).groups_keywords so the relationship is working?

But I want to get all of my Groups keywords so I do the following.

Group.find(1).keywords

But I get the error uninitialized constant Group::Keywords

How to generate thumbnail preview of pdf,xls files in rails3 using paperclip and ImageMagick?

model code:

class Discussion < ActiveRecord::Base

has_attached_file :file end

lundi 29 juin 2015

Devise two user models password reset

I'm using devise with two user models - an Employee model and Employer Model.

I'm having issues trying to get the password reset link to work with both models. Currently devise wildly send the password reset link to the users that belong to the Employee model and will not find users the belong to the Employer model.

Any suggestions on how to configure devise to work with both Models.

RVM ruby-1.9.2-p290, Symbol not found: _SSLv2_client_method

while trying to run the bundle install command in my project root directory here the error I am getting

I tried to running brew update but it doesn't help. Any help will be appreciated

bundle install

/Users/user123/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require':     dlopen(/Users/user123/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/x86_64-darwin11.4.2/openssl.bundle, 9): Symbol not found: _SSLv2_client_method (LoadError)
  Referenced from: /Users/user123/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/x86_64-darwin11.4.2/openssl.bundle
  Expected in: flat namespace
 in /Users/user123/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/x86_64-darwin11.4.2/openssl.bundle -  /Users/user123/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/x86_64-darwin11.4.2/openssl.bundle
    from /Users/user123/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /Users/user123/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/openssl.rb:17:in `<top (required)>'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/fetcher.rb:288:in `rescue in request'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/fetcher.rb:278:in `request'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/fetcher.rb:257:in `fetch'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/fetcher.rb:234:in `use_api'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/source/rubygems.rb:228:in `block in remote_specs'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/source/rubygems.rb:228:in `select'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/source/rubygems.rb:228:in `remote_specs'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/source/rubygems.rb:167:in `fetch_specs'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/source/rubygems.rb:66:in `specs'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/definition.rb:216:in `block (2 levels) in index'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/definition.rb:213:in `each'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/definition.rb:213:in `block in index'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/index.rb:9:in `build'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/definition.rb:209:in `index'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/definition.rb:203:in `resolve'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/definition.rb:133:in `specs'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/definition.rb:122:in `resolve_remotely!'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/installer.rb:82:in `run'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/installer.rb:15:in `install'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/cli/install.rb:76:in `run'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/cli.rb:146:in `install'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/vendor/thor/command.rb:27:in `run'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/vendor/thor/invocation.rb:121:in `invoke_command'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/vendor/thor.rb:363:in `dispatch'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/vendor/thor/base.rb:440:in `start'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/cli.rb:9:in `start'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/bin/bundle:20:in `block in <top (required)>'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/lib/bundler/friendly_errors.rb:5:in `with_friendly_errors'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.6.0/bin/bundle:20:in `<top (required)>'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/bin/bundle:19:in `load'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/bin/bundle:19:in `<main>'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/bin/ruby_noexec_wrapper:14:in `eval'
    from /Users/user123/.rvm/gems/ruby-1.9.2-p290/bin/ruby_noexec_wrapper:14:in `<main>'

ActiveRecord attribute is nil but database has value

I am working with Ruby on Rails, fairly new with Rails. Whenever I query objects, the created_at and updated_at fields are nil on the ruby object.

When I use sqlitebrowser to examine the backend, I can see that the field has a value. I am using rails console to figure this out.

jwilliam@ubuntu:~/rails/devminder$ rails console
Loading development environment (Rails 4.1.8)
2.2.2 :001 > Instance.all
  Instance Load (1.1ms) SELECT "instances".* FROM "instances"
 => #<ActiveRecord::Relation [#<Instance id: 1, title: "test" ec2id: "", created_at: nil, updated_at: nil, can_ice: 0>]>
2.2.2 :002 > SQLite3::Development.new('db/development.sqlite3').execute("select instances.* from instances")
 => [[1,"test", "", "2015-06-29 15:35:10.012611", "2015-06-29 15:35:10.012611", 0]]

When I execute Instance.all I see that I am getting nil for created_at and updated_at, however executing the query directly to SQLite3 shows that there are values, and it is not mapping them to ActiveRecord attributes properly.

I have a Rails project, using a SQLite3 backend. I am sure I have done something to jam this app up, but I am trying to figure it out.

file app/models/instance.rb

class Instance < ActiveRecord::Base
end

file app/models/schedule.rb

class Schedule < ActiveRecord::Base
   #table schedules has an instance_id field... 
   belongs_to :instance
end

Git push origin +master deleted many commits from repo

I was just making a change on my webpage but had a conflict I tried to resolve on my server. After fixing my conflict, I committed, then I pulled. The pull said it was up to date. Then attempting to push I got this:

git push origin master

To git@gitlab.com:admenergy/admnet.git ! [rejected] master -> master (non-fast-forward) error: failed to push some refs to 'git@gitlab.com:admenergy/admnet.git' To prevent you from losing history, non-fast-forward updates were rejected Merge the remote changes (e.g. 'git pull') before pushing again. See the 'Note about fast-forwards' section of 'git push --help' for details.

So I tried to force it, I ran this:

git push origin +master

Total 0 (delta 0), reused 0 (delta 0) To git@gitlab.com:admenergy/admnet.git + 94eec00...8002858 master -> master (forced update)

But then I logged into my git repository and all it did was delete my last 59 commits.... Can someone explain to me why this happened? Also, how should I go about fixing it from here?

Thank you,

JSONFixture could not be loaded - 404 Jasmine, Rails

We have specs in Jasmine using jasmine-rails and jasmine-jquery-rails gems.

routes.rb has:

mount JasmineRails::Engine => "/specs" if defined?(JasmineRails)

jasmine.yml:

# path to parent directory of src_files
# relative path from Rails.root
# defaults to app/assets/javascripts
src_dir: "app/assets/javascripts"

# list of file expressions to include as source files
# relative path from src_dir
src_files:
 - "application.js"

# path to parent directory of spec_files
# relative path from Rails.root
# defaults to spec/javascripts
spec_dir: spec/javascripts

# list of file expressions to include as helpers into spec runner
# relative path from spec_dir
helpers:
  - "helpers/**/*.{js.coffee,js,coffee}"

# list of file expressions to include as specs into spec runner
# relative path from spec_dir
spec_files:
  - "fixtures/json/*.js"
  - "fixtures/json/cso_fee_coupons.js"
  - "spec_helper.js.coffee"
  - "**/*[Ss]pec.{js.coffee,js,coffee}"

# path to directory of temporary files
# (spec runner and asset cache)
# defaults to tmp/jasmine
tmp_dir: "tmp/jasmine"

spec/javascripts/fixtures/json holds all the fixtures with js extension.

Due to some legacy reasons - the Gemfile is pointing at fixed versions of these gems which are quite old:

  gem "jasmine-rails", "= 0.5.6"
  gem "jasmine-jquery-rails", "= 1.5.9"

The spec suite runs perfectly on other laptops. It appears to be a problem local to my machine, security settings or something. I've enabled local file system config in Firefox as directed by an SO post because XHR requests are blocked by default due to security reasons. I've checked file permissions, I've checked permissions on running the application, the specs fail from the command line or from the browser (rake spec:javascript or running at localhost:3000/specs). No matter what I try the error message below is reported for EVERY fixture file that we have. My co-worker's laptop - no errors. They are identical MBPs ordered exactly the same time. They run the same version of FF. We compared directories and don't see any differences beyond the username.

I am really stuck on what could be the difference on just my machine. CircleCI runs spec:javascript as well and it passes....

    Failing 1 spec1 spec | 1 failing
App.ApplicationDetailsBasicInfo encountered a declaration exception.
Error: JSONFixture could not be loaded: spec/javascripts/fixtures/json/application_details_response.json (status: error, message: undefined) in http://localhost:3001/assets/jasmine-jquery.js?body=1 (line 240)
jasmine.JSONFixtures.prototype.loadFixtureIntoCache_/<.error@http://localhost:3001/assets/jasmine-jquery.js?body=1:240:15
jQuery.Callbacks/fire@http://localhost:3001/assets/jquery.js?body=1:975:10
jQuery.Callbacks/self.fireWith@http://localhost:3001/assets/jquery.js?body=1:1085:7
done@http://localhost:3001/assets/jquery.js?body=1:7806:1
.send/callback@http://localhost:3001/assets/jquery.js?body=1:8519:8
.send@http://localhost:3001/assets/jquery.js?body=1:8525:7
.ajax@http://localhost:3001/assets/jquery.js?body=1:7987:5
jasmine.JSONFixtures.prototype.loadFixtureIntoCache_@http://localhost:3001/assets/jasmine-jquery.js?body=1:231:1
jasmine.JSONFixtures.prototype.getFixtureData_@http://localhost:3001/assets/jasmine-jquery.js?body=1:223:5
jasmine.JSONFixtures.prototype.read@http://localhost:3001/assets/jasmine-jquery.js?body=1:212:7
jasmine.JSONFixtures.prototype.proxyCallTo_@http://localhost:3001/assets/jasmine-jquery.js?body=1:246:12
global.getJSONFixture@http://localhost:3001/assets/jasmine-jquery.js?body=1:704:12
@http://localhost:3001/assets/generated/ApplicationDetailsBasicInfo_spec.js?body=1:4:29
jasmine.Env.prototype.describe@http://localhost:3001/assets/jasmine.js?body=1:819:5
describe@http://localhost:3001/assets/jasmine.js?body=1:603:10
@http://localhost:3001/assets/generated/ApplicationDetailsBasicInfo_spec.js?body=1:2:3
@http://localhost:3001/assets/generated/ApplicationDetailsBasicInfo_spec.js?body=1:1:1

Rails: CKEditor, paperclip, and s3 errors

I tried adding the editor to my rails app using amazons3 and paperclip but im having errors. If I cant get this to work, what other editors are available that would work? Here is the error I got below

ArgumentError in Ckeditor::PicturesController#create
missing required :bucket option

Extracted source (around line #218):
216
217
218
219
220
221

        @bucket = @options[:bucket] || s3_credentials[:bucket]
        @bucket = @bucket.call(self) if @bucket.respond_to?(:call)
        @bucket or raise ArgumentError, "missing required :bucket option"
      end

      def s3_interface

I'm not sure what to do as I followed these steps.

gem 'paperclip'
gem 'ckeditor'

then bundled

rails generate ckeditor:install --orm=active_record --backend=paperclip

rake migrated

mount Ckeditor::Engine => "/ckeditor"

added this to application.js

//= require ckeditor/init

added this to the view page

    <%= f.cktext_area :content, :class => "form-control" %>


These are the files created and their configuration

/Ckeditor/Picture.rb

class Ckeditor::Picture < Ckeditor::Asset
  has_attached_file :data,
                    :url  => ":s3_domain_url",
                    :path =>         "/:class/:attachment/:id_partition/:style/:filename",
                    :styles => { :content => '800>', :thumb => '118x100#' }

  validates_attachment_presence :data
  validates_attachment_size :data, :less_than => 2.megabytes
  validates_attachment_content_type :data, :content_type => /\Aimage/

  def url_content
    url(:content)
  end
end

/Ckeditor/attachment_file.rb

  class Ckeditor::AttachmentFile < Ckeditor::Asset
  has_attached_file :data,
                    :url => "/ckeditor_assets/attachments/:id/:filename",
                    :path => ":rails_root/public/ckeditor_assets/attachments/:id/:filename"

  validates_attachment_presence :data
  validates_attachment_size :data, :less_than => 100.megabytes
  do_not_validate_attachment_file_type :data

  def url_thumb
    @url_thumb ||= Ckeditor::Utils.filethumb(filename)
  end
end

/Ckeditor/asset.rb

class Ckeditor::Asset < ActiveRecord::Base
  include Ckeditor::Orm::ActiveRecord::AssetBase
  include Ckeditor::Backend::Paperclip
end


I use these lines of code in development.rb and production.rb and I haven't had any issues with paperclip before with s3.

config.paperclip_defaults = {
:storage => :s3,
:s3_protocol => 'http',
:bucket => ENV['AWS_BUCKET'],
:s3_credentials => {
  :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
  :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
}
    }

This is the paperclip.rb file

Paperclip::Attachment.default_options[:url] = ':s3_domain_url'
Paperclip::Attachment.default_options[:path] = '/:class/:attachment/:id_partition/:style/:filename'

View not coming in rails application

I had one existing rails application and i was asked to add a few features in this application.

So I wrote a view file,action for the new feature.

But I straight away added .html.erb file and my action in the existing file directories but now view for the new feature is not coming.

Is it because i added the files directly rather than running a command

I have also modified the route file.

Rails not creating object correctly

I'm new to Ruby on Rails and I can't understand why the following simple command is not working.

2.2.1 :031 > Category.new(:name => 'Example')
 => #<Category id: nil, name: nil, created_at: nil, updated_at: nil> 

I define :name as 'Example' but the object created has name set to nil. What I am trying to do is to create a new object and then persist it to the database from Category model .

It is probably simple but does not make sense to a beginner !

Thanks

ubuntu server 14.04 not rendering local characters generated using wicked_pdf

I have a pdf page containing Ethiopian characters. It works perfectly in ubuntu desktop 14.04, but when i deploy it to ubuntu server 14.04 the characters are not being displayed. I am using wicked_pdf gem to generate the pdf page.

I am stuck here for the whole day. Any help is welcomed.

Devise create admins only with admin permission

In my Ruby on Rails application i use Devise for authenticate the admins.

In this moment everyone can create an account as admin, or rather they have access to the standard devise routes for create,destroy,edit,sign_in,sign_up,sign_out.

I want that only an admin can create another admin's account, so how can i handle this situation?

dimanche 28 juin 2015

How to create an association between devise user model and new model in rails?

I can easily do singnin and singup process in my application but I am not able to understand how to pass user_id in my new model. After integrating devise successfully I followed the following steps:

Generate new model with the name of book

rails generate model books name:string users:references

It generated book class in models folder along with migration class.

Model class

class Book < ActiveRecord::Base
 belongs_to :user
end

Migration class

class CreateBooks < ActiveRecord::Migration
 def change
  create_table :books do |t|
  t.string :name
  t.references :user, index: true, foreign_key: true
  t.timestamps null: false
  end
end

Now, I add

has_many :books, :dependent => :destroy

in user model class to make a proper one to many association.

After creating these classes I run rake db:migrate and it created a new schema in the project. After creating schema I wrote seed file to confirm whether my database is working or not. It was working fine. I can see the new entries in my Book and user table along with user_id in Book table.

Routes class

sampleApplicationUI::Application.routes.draw do
 devise_for :users
 resources :books, except: [:edit]
end

Now, I added a book_controller class and here is the code:

Book controller class

class BooksController < ApplicationController
before_action :authenticate_user!

 def index
  @book = Book.all
 end

def new
 @book = Book.new
end

def create
 @book = Book.new(filtered_params)
 if @book.save
   redirect_to action: 'index'
 else
   render 'new'
 end
end

private
def filtered_params
 params.require(:book).permit(:name, :user_id)
end
....

books/new.html.erb

<%= form_for @book, as: :book, url: book_path do |f|  %>

<div class="form-group">
  <%= f.label :Name %>
  <div class="row">
    <div class="col-sm-2">
      <%= f.text_field :name, class: 'form-control' %>
    </div>
  </div>
</div>

  <div class="row">
  <div class="col-sm-6">
    <%= f.submit 'Submit', class: 'btn btn-primary' %>
  </div>
</div>

I followed some blogs and they were mentioning to do following changes in book_controller class to access user_id and save into book table:

changes in book controller class

def new
  @book = Book.new(user: current_user)
end

but here I am getting No variable defined current_user :(

Please let me know what I am doing wrong here and How can i access user.user_id in book controller class.

Thanks for your time!

Angular POST request sending info in parameters that I did not specify and Rails throwing errors about it

So I am currently making a user create a new account on a Rails app using devise.

The registration is handled by Angular on the client side.

Here is the angular code for it:

This method is in a controller

$scope.create = (isValid) ->
            $scope.submitted = true
            if isValid
                UserService.create_user(user: {
                    name: $scope.name,
                    email: $scope.email,
                    password: $scope.password,
                    password_confirmation: $scope.password_confirmation
                }, submit: 'Sign up', (response)->
                    console.log(response)
                )
                console.log(isValid)
                #@userService.createUser(user, $scope)
            else

@Fit.service 'UserService', [
    '$resource', '$http', '$routeParams', 'Common',
    ($resource, $http, $routeParams, Common) ->
        $resource '/users/:id/:options.json', { id: '@id', options: '@options' },
            create_user: {
                method: 'POST'
            },
            set_avatar: {
                method: 'POST'
            },
            update_user: {
                method: 'PATCH'
            },
            find: {
                method: 'GET'
            },
            update_role: {
                method: 'PATCH'
            }

]

Now when I send the request on the way I get this in my server log:

Started POST "/users.json" for 127.0.0.1 at 2015-06-28 22:45:35 +0300
Value for params[:user][:password] was set to nil, because it was one of [], [null] or [null, null, ...]. Go to http://ift.tt/1vKj4i4 for more information.
Processing by Devise::RegistrationsController#create as JSON
  Parameters: {"user"=>{"name"=>"foo", "email"=>"foo@bar.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "submit"=>"Sign up", "registration"=>{"user"=>{"name"=>"foo", "email"=>"foo@bar.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "submit"=>"Sign up"}}
   (0.2ms)  BEGIN
  User Exists (0.4ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = 'foo@bar.com' LIMIT 1
   (0.2ms)  ROLLBACK
Completed 422 Unprocessable Entity in 5ms (Views: 0.2ms | ActiveRecord: 0.8ms)

Now there are two things wrong with this log. First of all in the parameters section I have a list of the same values that I put under user object also under the registration object. Now I have no idea where that came from.

As you can see in the picture, chrome debugger shows that no such params where sent. Only the user one. Yet rails logs show differently.

My request params

Now the second problem here is that for some reason the log is throwing errors about the params I sent and I also get this response:

{"errors":{"password":["can't be blank"],"password_confirmation":["doesn't match Password"]}}

What could be causing these issues? I checked up what is being sent if I use .erb user creation with a new Devise project and there it also sent all the params under the user object.

Why does it get "undefined method `videoId'" sometimes?

I'm trying to load the search result of Youtube with using its API.
It looks working fine so far but it sometimes get this error

ActionView::Template::Error (undefined method `videoId' for #<Google::APIClient::Schema::Youtube::V3::ResourceId:0x000000072afcb8>):

I'm just wondering if YouTube won't provide its videoId sometimes under some particular situation?

How can I avoid this problem?

CONTROLLER

. 
.
.
@search_response = client.execute!(
  :api_method => youtube.search.list,
  :parameters => {
    :part => 'snippet',
    :q => 'cat',
    :maxResults => 10,
    :order => 'date',
    :pageToken => pageToken
  }
)
.
.
.

VIEW

<% @search_response.data.items.each do |video| %>
    ID: <%= video.id.videoId %><br />
    Title: <%= video.snippet.title %><br />
    Description: <%= video.snippet.description %><br />
    <img src="<%= video.snippet.thumbnails.high.url %>" with="480" height="360"><br />
    <br />
    <br />
<% end %>


<%= debug @search_response.data.items %>

'rails generate controller' doesn't create any files

The command succeeds in running, and says that the files are created, however there are no files created, and running the command again says that they already exist.

after rails generate controller, at ~/Desktop/Projects/RailsTutorial:

  create  app/controllers/static_pages_controller.rb
  invoke  erb
  create    app/views/static_pages
  invoke  test_unit
  create    test/controllers/static_pages_controller_test.rb
  invoke  helper
  create    app/helpers/static_pages_helper.rb
  invoke    test_unit
  invoke  assets
  invoke    coffee
  create      app/assets/javascripts/static_pages.coffee
  invoke    scss
  create      app/assets/stylesheets/static_pages.scss

ls at ~/Desktop/Projects/RailsTutorial/app/controllers:

  application_controller.rb  concerns

Why this won't fetch particular page of the result set?

Following youtube's official API document, I made this code below.
It shows fine if I take off

:pageToken => 5

How can I fetch particular page of the result sets?(I mean pagination here)

Original Code

@search_response = client.execute!(
  :api_method => youtube.search.list,
  :parameters => {
    :part => 'snippet',
    :q => 'cat',
    :maxResults => 10,
    :order => 'date',
    :pageToken => 5
  }
)

What would be the best way to fetch information of Youtube result searched by a query?

This gem yourub is not compatible with fetching particular page of the result set(pagination)

Is there any other way to fetch data sets of the Youtube result searcged by a query?

I'd like to select the page number of the result set, and the maximum number of the records to show in one query.

samedi 27 juin 2015

Why is it too slow to fetch the records?

I'm using the gem called 'yourub' to fetch information of multiple videos narrowed down by particular keyword.

My code is just like this and it works fine but too slow until the result start showing up on the page.
Is it because I'm using the gem? Does it get faster if I do the same thing with native way of using "google-api-client" gem? If so how can I replace my original?

P.S. According to the document of 'yourub', it only can fetch up to 50 videos:( and it cannot even choose which page of the result to show with pagination select :(

My code(View)

<% client = Yourub::Client.new %>

<% client.search(query: "cat", order: "date", max_results: 30) do |video| %>

Video ID:<%= video["id"] %> <br />
Title: <%= video["snippet"]["title"] %><br />
<img src="<%= video["snippet"]["thumbnails"]["high"]["url"] %>" with="480" height="360"><br />
----------------------------------------------------------------------------------------------<br />
  <br />
<% end %>

Header of the application not appering as per the condition in _header.html.erb

I am following ruby on rails tutorials by michael harlt. I completed my user authentication system and it also working fine but according to the code of my header file it is not supposed to show "Users" and "Accounts" link until and unless the user is logged in.But as soon as I navigate to the login page or sign up page it is showing both these links even if the user is not logged in.

I am not getting any error while launching app in my browser Here I am posting all the relevant files. Any help would be appreciated.Thanks in advance ! For any other information please let me know.

session_controller.rb

class SessionsController < ApplicationController

  def new
  end

  def create
    user = User.find_by_email(params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      log_in user
      remember user
      redirect_to user
    else
      flash.now[:danger] = 'Invalid email/password combination'
      render 'new'
    end
  end

  def destroy
    log_out if logged_in?
    redirect_to home_path
  end
end

sessions_helper.rb

module SessionsHelper

  # Logs in the given user.
  def log_in(user)
    session[:user_id] = user.id
  end

  # Remembers a user in a persistent session.
  def remember(user)
    user.remember
    cookies.permanent.signed[:user_id] = user.id
    cookies.permanent[:remember_token] = user.remember_token
  end

  # Returns the user corresponding to the remember token cookie.
  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by_id(user_id)
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by_id(user_id)
      if user && user.authenticated?(cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

  # Returns true if the user is logged in, false otherwise.
  def logged_in?
    !current_user.nil?
  end

  # Forgets a persistant session
   def forget(user)
     user.forget
     cookies.delete(:user_id)
     cookies.delete(:remember_token)
   end

   # Log Out Current User
  def log_out
    session.delete(:user_id)
    @current_user = nil
  end
end

_header.html.erb

<header class="navbar navbar-fixed-top navbar-inverse">
  <div class="container">
    <%= link_to "sample app", home_path, id: "logo" %>
    <nav>
      <ul class="nav navbar-nav navbar-right">
        <li><%= link_to "Home", home_path %></li>
        <li><%= link_to "Help", help_path %></li>

        <% if logged_in? %>
          <li><%= link_to "Users", '#' %></li>
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">
              Account <b class="caret"></b>
            </a>
            <ul class="dropdown-menu">
              <li><%= link_to "Profile", current_user %></li>
              <li><%= link_to "Settings", '#' %></li>
              <li class="divider"></li>
              <li>
                <%= link_to "Log out", logout_path, method: "delete" %>
              </li>
            </ul>
          </li>
        <% else %>
          <li><%= link_to "Log in", login_path %></li>
        <% end %>
      </ul>
    </nav>
  </div>
</header>

user.rb

class User < ActiveRecord::Base
  attr_accessor :remember_token
  before_save { self.email = email.downcase }
  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, length: { minimum: 6 }

  # Returns the hash digest of the given string.
  def User.digest(string)
    cost = BCrypt::Engine::MIN_COST
    BCrypt::Password.create(string, cost: cost)
  end

  # Returns a random token.
  def User.new_token
    SecureRandom.urlsafe_base64
  end

  # Remembers a user in the database for use in persistent sessions.
  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end

  # Returns true if the given token matches the digest.
  def authenticated?(remember_token)
     return false if remember_digest.nil?
    BCrypt::Password.new(remember_digest).is_password?(remember_token)
  end

  def forget
    update_attribute(:remember_digest, nil) 
  end
end

Rails form_tag to show action

I have a Rails app where I have a partial that I want a dropdown in so when a user is selected it will do a get method to the urls /timecards/:user_id which will be the controller's show method passing in the User's id field. I'm having a hard time with my paths in the form_tag and could use some help.

Here is my partial in the view:

<%= form_tag timecard_path, :method => :get do %>
  <%= select_tag options_from_collection_for_select(User.employee.order("username ASC"), :id, :username) %>
  <%= submit_tag "View Employee", class: "btn btn-primary" %>
<% end %>

From rake routes I get the following output:

timecards GET    /timecards(.:format)                 timecards#index
                           POST   /timecards(.:format)                 timecards#create
              new_timecard GET    /timecards/new(.:format)             timecards#new
             edit_timecard GET    /timecards/:id/edit(.:format)        timecards#edit
                  timecard GET    /timecards/:id(.:format)             timecards#show
                           PUT    /timecards/:id(.:format)             timecards#update
                           DELETE /timecards/:id(.:format)             timecards#destroy

Here is my controller: timecards_controller.rb

class TimecardsController < ApplicationController
before_filter :disallow_clients, :disallow_medics, :disallow_employee, :disallow_supervisor

  def index
    @clock_events = ClockEvent.includes(:user).search(params[:search])
    respond_to do |format|
        format.html do
          @clock_events = @clock_events.paginate(:per_page => params[:per_page] || 20, :page => params[:page]).order('users.username asc').order('clock_in desc')
        end
        format.csv { send_data ClockEvent.to_csv(@clock_events.order('users.username asc').order('clock_in desc')) }
      end
  end

  def new
    @clock_event = ClockEvent.new
  end

  def create
    parse_times!
    @clock_event = ClockEvent.new(params[:clock_event])

     if @clock_event.save
       redirect_to timecard_path(@clock_event.user.id), notice: "Entry added for #{@clock_event.user.username}".html_safe
      else
       render :new, notice: "Time Card Entry failed to Save".html_safe
      end
  end

  def show
    @user = User.find(params[:id])
    @clock_events = @user.clock_events.search(params[:search])
      respond_to do |format|
        format.html do
          @clock_events = @clock_events.paginate(:per_page => params[:per_page] || 5, :page => params[:page]).order('clock_in DESC')
        end
        format.csv { send_data ClockEvent.to_csv(@clock_events.order('clock_in desc')) }
        format.pdf do
          pdf = TimeCardPdf.new(@clock_events, @user)
          send_data pdf.render, filename: "timecard-#{@user.username}",
                                type: "application/pdf",
                                disposition: "inline"
         end
      end
  end

  def edit
    @user = User.find(params[:id])
    @clock_events = @user.clock_events.search(params[:search]).order("clock_in ASC").paginate(:per_page => 10, :page => params[:page])
  end

  def update
    parse_times!
    @clock_event = ClockEvent.find(params[:clock_event][:id])
    if @clock_event.update_attributes(params[:clock_event])
        redirect_to edit_timecard_path(@clock_event.user.id), notice: "Updated Successfully".html_safe
    else
        redirect_to :back, notice: "Woops.".html_safe
    end
  end

  private

  def parse_times!
    params[:clock_event].parse_time_select! :clock_in if params[:clock_event].has_key? 'clock_in(5i)'
    params[:clock_event].parse_time_select! :clock_out if params[:clock_event].has_key? 'clock_out(5i)'
  end

end

So I believe I'm calling the path properly in the form_tag but when I load the page I get the error: No route matches {:action=>"show", :controller=>"timecards"} Even though there is a show action in the timecards_controller.

I think something I have to set the form_tag for an explicit url and somehow pass in the :id of the user in the params. But I'm a bit stuck on how to do this.

So to summarize. When I have the dropdown, I select a user, click "View Employee", and that should go to the show action in timecards_controller.rb with the url of /timecards/3 (as an example). I've never used form_tag in this way before so passing a path or explicit url is a bit foreign to me.

Any help you can provide would be greatly appreciated. If you need further clarification or have questions, please ask.

Simple form input as dropdown not select box

I have a input with a collection that should display as a drop down but instead it's displaying as a select box. How do i make it a drop down?

<%= f.input :fund, collection: funds, prompt: 'Select Fund', label: false, input_html: { multiple: true } %>

vendredi 26 juin 2015

Input select not displaying as dropdown

I have a input with a collection that should display as a drop down but instead it's displaying as a slider with a scroll. How do i make it a drop down?

<%= f.input :fund, collection: funds, prompt: 'Select Fund', label: false, input_html: { multiple: true } %>

enter image description here

Inspection can't find model field method

I try to eliminate all warnings in all my code. I find this improves the quality of my code. This becomes problematic when the RubyMine inspections find an issue that I can't resolve. One of the most annoying is when I have a model instance and it complains it can't find the method for one of the fields. I'd be happy to do something silly or extra to get rid of the complaint, but I don't have any ideas why the inspection can't find one field out of ten on a record or how to convince the inspection this one is correct.

Collection select display as dropdown

I have a collection_select and want it to display as a dropdown but instead it keeps showing as a slider with a scroll. How do I make it a dropdown?

<%= f.collection_select :fund, funds, :id, :name, {}, {:multiple => true} %>

dependent => destroy on has_one not working

I must be overlooking something simple.

I have two models. They have a has_one association. I am trying to destroy the child has_one association but it's not working.

class Column
  has_one :subtable, :class_name => "Table", :foreign_key => :parent_id, :dependent => :destroy
end

// the parent_id column is on the `table` table
class Table
  belongs_to :parent_column, :class_name => "Column", :foreign_key => :parent_id
end

If I do

@column.destroy

The table doesn't get destroyed. What am I missing?

Rails Joins inherited relation

I have a relation with

MODEL USER

has_one :user_information
has_many :user_tags

MODEL USER_INFORMATION

BELONGS_TO :user

AND HAVE A MODEL

USER_TAG

belongs_to :user

question:

How to acess a ORDER BY USER_INFORMATION IS NOT NULL FROM USER_HAST_TAG with joins

NEED:

@USER_TAGS=UserTag.joins(:user).where(:active => true).order("user.user_information is not null desc")

Im Try with

@USER_TAGS=UserTag.joins(:user,{:usuario => :usuario_videos}).where(:active => true).order("user.user_information is not null desc")

ouput mysql Unknown column user.user_information

thanks for you help

Ruby on rails timeout message not showing when javascript is executed

I have a ruby on rails application that has the timeout time set to 30 minutes.

If 30 minutes have passed and you try to do something it returns to the login screen. This all works fine.

The problem I'm facing is with a javascript-table-refresh-button. If that button is clicked (and 30 minutes or more has passed) then we are redirected back to login. Problem is, in this case the error message doesn't show.

Any ideas how I can force the JS to show that error?

Rails- form_for url overrides default_form_options and renders default locale

This is my form:

= form_for @example, url: new_funnel_example_path, method: :get do |f| // here goes my form content end

and application_controller.rb

before_filter :set_locale

def set_locale
  I18n.locale = params[:locale] || I18n.default_locale
end

def default_url_options(options = {})
  return { locale: I18n.locale }.merge options
end

Root Cause: My form_for url helper overrides the default_url_options and because set_locale is invoked in before_filter(before every action call) it sets I18n.locale to I18n.default_locale and thereby changing the app to default locale .

It might work if I pass params[:locale] as a hidden variable - that would be tedious and will look ugly.So is there a neat fix for this ?

Rails Sorting the record based on the array passed in where condition

I want to sort my where condition result in the order i am passing the values in array . what i am doing is i have an array of ids

ids = [80, 20, 3, 91, 84, 90, 98, 97, 68, 99, 92, 73]

When i am passing this array to where condition like :

products = Product.where(id: ids)

its returning the result active record relation in different order (random order)something like :

=>[ 20 ,84, 3,98 , .............. ] 

(this is active record relation object i have mention only ids here )

But i want it to return the object in same order i am passing the the values like (In active record relation object not an array)

=> [80, 20, 3, 91, 84, 90, 98, 97, 68, 99, 92, 73]

How can i do this .

jeudi 25 juin 2015

I have a conflict with a dependent select

I have some issue with grouped_collection_select in rails 4, so I need your help.

I have this models:

class Event < ActiveRecord::Base
has_many :appointments
belongs_to :user
scope :evento_sin, -> { where(available: "1") }
end

class User < ActiveRecord::Base
has_many :events
has_many :appointments
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
     def medic_with_spec
        "#{especialidad}, #{name} #{lastname}"          
     end
end

and my view have:

<div class="field">
<%= f.label :user_id, "Médicos" %><br />
<%=select("appointment", "user_id", @usuarios.collect {|p|     [p.especialidad+" - "+p.lastname + ", " +p.name, p.id ] }, { include_blank: true }) %>
</div>

<div class="field">
<%= f.label :event_id, "Consultas Disponibles" %><br />
<%= f.grouped_collection_select :event_id, @usuarios.order(:name), 
:eventos.evento_sin, :id, :id, :start_time, include_blank: true %>

but I receive: undefined method `evento_sin' for :events:Symbol

What happen with this code?

Thanks for you help

Rails controller params conditionals - how to do this cleanly

I'm need to check a bunch of conditions in a controller method. 1) it's a mess and 2) it's not even hitting the right redirects.

def password_set_submit
  password_check = /^(?=.*[a-z]{1,})(?=.*[A-Z]{1,})(?=.*\d{1,}){8,}.+$/

  @user = User.find(session[:id])
    if params[:password] && params[:password_confirmation] && params[:username] && params[:old_password]
        if params[:password] == params[:password_confirmation] && params[:password] =~ password_check

          # do some api stuff here

        if @user.save
          flash[:success] = 'Password updated.'
          redirect_to login_path and return
        end
      end
      if params[:password] != params[:password_confirmation]
        flash[:error] = 'Passwords did not match.'
        redirect_to password_set_path and return
      end
      if params[:password] == params[:password_confirmation] && params[:password] !~ password_check
        flash[:error] = 'Passwords did not match password criteria.'
        redirect_to password_set_path and return
      end
    end
  else
    flash[:error] = 'Please fill all inputs.'
    redirect_to password_set_path and return
  end
end

This needs to do the following:

1) If less than four params submitted, redirect and display 'Fill all inputs'

2) If password and password confirmation don't match each other, redirect and display 'Password did not match'

3) If password and password confirmation match each other but do not match criteria, redirect and display 'Passwords did not match criteria'

4) If password and password confirmation match each other and match criteria, make api call and redirect to login

I'm out of if/else ideas and I hope cleaning this up will help me nail the redirects correctly.

How to limit test data creation when running two tests with FactoryGirl

I have 48 records being created by FactoryGirl, the records use sequence so that they are all unique.

When I run a test, I get all 48 records being created with names as follow Skill_1 to Skill_48.

When I run a subsequent test, I get an additional 48 records created, these have different new values, Skill_49 to Skill_96

I really want my 2nd test to use the same data set as the first test but cannot figure out how to do so

I've included my code here

# Factory
FactoryGirl.define do
 factory :skill do

  provisioned true

  trait :skill do
   skill true
  end
  trait :language do
   language true
  end
  trait :qualification do
   qualification true
  end
  trait :role do
   role true
  end
  trait :personal_attribute do
   personal_attribute true
    end

  sequence :name do |n|n
   type = '(skill)'

   if language
    type = '(language)'
   end
   if qualification
    type = '(qualification)'
   end
   if role
    type = '(role)'
   end
   if personal_attribute
    type = '(personal_attribute)'
   end

   "skill#{n} #{type}"
  end

 end
end

UNIT TEST is HERE

describe SkillQueryService do

  let(:skills) { create_list(:skill, 10, :skill) }
  let(:languages) { create_list(:skill, 2, :language) }
  let(:qualifications) { create_list(:skill, 3, :qualification) }
  let(:roles) { create_list(:skill, 4, :role) }
  let(:personal_attributes) { create_list(:skill, 5, :personal_attribute) }

  let(:unprovisioned_skills) { create_list(:skill, 10, :skill, :provisioned  => false) }
  let(:unprovisioned_languages) { create_list(:skill, 2, :language, :provisioned  => false) }
  let(:unprovisioned_qualifications) { create_list(:skill, 3, :qualification, :provisioned  => false) }
  let(:unprovisioned_roles) { create_list(:skill, 4, :role, :provisioned  => false) }
  let(:unprovisioned_personal_attributes) { create_list(:skill, 5, :personal_attribute, :provisioned => false) }

  context 'sugguest' do

    it 'returns 20 suggested provisioned skills' do

      # Build TEST data

      service = SkillQueryService.new

      rows = service.suggest('skill')

      # rows.each do |r|
      #   display_skill(r)
      # end
      # THIS CODE PRINTS OUT SKILLS 1-48
      expect(rows.length).to eq(20)

    end


    it 'returns 20 suggested (UN)-provisioned skills' do

      # Build TEST data
      full_data_set

      service = SkillQueryService.new

      rows = service.suggest('skill')

      # rows.each do |r|
      #   display_skill(r)
      # end
      # THIS CODE PRINTS OUT SKILLS 49-96
      # HOW do I get it to have the same data as above, SKILLS 41-48

      expect(rows.length).to eq(20)
    end

  end

  def full_data_set
      skills
      languages
      qualifications
      roles
      personal_attributes

      unprovisioned_skills
      unprovisioned_languages
      unprovisioned_qualifications
      unprovisioned_roles
      unprovisioned_personal_attributes

  end

  def display_skill(skill)
    PL.kv 'name', skill.name
    PL.kv 'provisioned', skill.provisioned
    PL.kv 'skill', skill.skill
    PL.kv 'language', skill.language
    PL.kv 'qualification', skill.qualification
    PL.kv 'role', skill.role
    PL.kv 'personal_attribute', skill.personal_attribute
    PL.line
  end

  def display_skills

    PL.line
    Skill.all.each do |r|
      display_skill(r)
    end
  end

end

Ruby on Rails resource routes, use slug instead of id

So i'm looking for a solution that would help me achieve the following with rails resource:

'/admin/articles/:slug/edit'

as opposed to

'/admin/articles/:id/edit'

I'm looking for rails resource routes and not the other kinds of routes.(http://ift.tt/1zOqALl)

Just wanted to know if it was possible. If so, how?

Thanks a bunch in advance

Rails Bad Request Bad Uri Due to Curly Brackets

I need my url to allow curly brackets. Like so

http://localhost:3000/?target={target_id}

The reason for this is that the {target_id} param will be replaced later by a third party site. I will not read that parameter I just need the site to load when the url looks this way.

currently I get this messege

Bad Request

Bad URI '?target={target_id}`

How do I get WeBrick to ignore the curly brackets in the url and display the site?

set created_at with local time zone in rails

Set the created_at to local time zone. I deployed my app in heroku. But while creating creating record created_at is taking heroku time but not local time. For example: in heroku time is: 26-06-2015 but in my local machine time is: 25-06-2015

I want to store my local machine time not heroku time. I tried to put the below code in application.rb

  config.time_zone = 'Eastern Time (US & Canada)'
  config.active_record.default_timezone = :local

But not working. Can anyone help me out of this

js alert is calling 2 times

I had a problem that I am getting every javascript alert 2times and js calling is also occurring 2 times.

what Can be the root cause?

I checked by git status and there is no file which can be modified and on other system same project is working fine.

Please help me to understand what causing this issue?

Exporting to CSV and Summing hours in Ruby on Rails

I have a Rails 3.2.21 app where I'm building time clock functionality. I'm currently writing a to_csv method that should do the following:

Create a header row with column names Iterate through a block of input (records) and display the employee username, clock_in, clock_out, station, and comment objects, then finally on the last line of the block display the total hours.

In between each user I want to display a sum of their total hours. As you can see in the to_csv method I'm able to get this to work "hackish" by shoveling an array of csv << [TimeFormatter.format_time(ce.user.clock_events.sum(&:total_hours))] into the CSV. The end result is it does give me the proper total hours for each employee's clock_events, but it repeats it after every entry because I'm obviously iterating over a block.

I'd like to figure out a way to abstract this outside of the block and figure out how to shovel in another array that calculates total_hours for all clock events by user without duplicate entries.

Below is my model, so if something is not clear, please let me know. Also if my question is confusing or doesn't make sense let me know and I'll be happy to clarify.

class ClockEvent < ActiveRecord::Base
  attr_accessible :clock_in, :clock_out, :user_id, :station_id, :comment
  belongs_to :user
  belongs_to :station
  scope :incomplete, -> { where(clock_out: nil) }
  scope :complete, -> { where("clock_out IS NOT NULL") }
  scope :current_week, -> {where("clock_in BETWEEN ? AND ?", Time.zone.now.beginning_of_week - 1.day, Time.zone.now.end_of_week - 1.day)}
  scope :search_between, lambda { |start_date, end_date| where("clock_in BETWEEN ? AND ?", start_date.beginning_of_day, end_date.end_of_day)}
  scope :search_by_start_date,  lambda { |start_date| where('clock_in BETWEEN ? AND ?', start_date.beginning_of_day, start_date.end_of_day) }
  scope :search_by_end_date, lambda { |end_date| where('clock_in BETWEEN ? AND ?', end_date.beginning_of_day, end_date.end_of_day) }

  def punch_in(station_id)
    self.clock_in = Time.zone.now
    self.station_id = station_id
  end

  def punch_out
    self.clock_out = Time.zone.now
  end

  def completed?
    clock_in.present? && clock_out.present?
  end

  def total_hours
    self.clock_out.to_i - self.clock_in.to_i
  end    

  def formatted_clock_in
    clock_in.try(:strftime, "%m/%d/%y-%H:%M")
  end

  def formatted_clock_out
    clock_out.try(:strftime, "%m/%d/%y-%H:%M")
  end

  def self.search(search)
    search ||= { type: "all" }

    results = scoped

    # If searching with BOTH a start and end date
    if search[:start_date].present? && search[:end_date].present?
      results = results.search_between(Date.parse(search[:start_date]), Date.parse(search[:end_date]))

      # If search with any other date parameters (including none)
    else
      results = results.search_by_start_date(Date.parse(search[:start_date])) if search[:start_date].present?
      results = results.search_by_end_date(Date.parse(search[:end_date])) if search[:end_date].present?
    end
    results
  end

  def self.to_csv(records = [], options = {})
    CSV.generate(options) do |csv|
      csv << ["Employee", "Clock-In", "Clock-Out", "Station", "Comment", "Total Shift Hours"]
      records.each do |ce|
        csv << [ce.user.try(:username), ce.formatted_clock_in, ce.formatted_clock_out, ce.station.try(:station_name), ce.comment, TimeFormatter.format_time(ce.total_hours)] 
        csv << [TimeFormatter.format_time(ce.user.clock_events.sum(&:total_hours))]      
      end
      csv << [TimeFormatter.format_time(records.sum(&:total_hours))]
    end
  end

end

How to use build for adding to ActiveRecord collection

I have a model called PhoneItems which has many CallingTimes. To disable the has_many autosave functionality I had to start using the build method.

phone_queue_items.calling_times.build

so that when the edit form is closed, the calling time isn't automatically saved. Now I have the following problem. I want to be able to push a second calling_time to the PhoneItem object, however the following is not working:

phone_queue_items.calling_times << CallingTimes.build

nor phone_queue_items.calling_times.build

Is there any way to do build more than one calling time in the phone_queue_item object?

How to fix Ruby on Rails obj != nil error

I'm trying to ensure that an object is not nil in Ruby on Rails and I'm getting this error:

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

This is what the object looks like in the debugger (it is not nil):

enter image description here

How do I correctly check for nil in this case? All cases?

I've found some similar posts but not this specific case: Check for nil gives error, and Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id.

How do I correctly check for nil in this case?

ActiveRecord: has_many relationship returns Array instead of ActiveRecord::Relation

I have the following code:

class User < ActiveRecord::Base
  has_many :transactions
end

class Transaction < ActiveRecord::Base
  belongs_to :user
  belongs_to :owner, class_name: 'User'

  scope :user, ->(user) { where('user_id = ?', user.id) }
  scope :owner, ->(user) { where('owner_id = ?', user.id) }
  scope :active, where(is_active: true)
end

If I type the following in the console I have:

Transaction.user(User.first).class # ActiveRecord::Transaction OK
User.first.transactions.class # Array KO
User.first.transactions.active.class # ActiveRecord::Transaction OK
User.first.transactions.where(used_id: User.first.id).class # ActiveRecord::Transaction OK
User.first.transactions.owner(User.first) # ERROR: 

NoMethodError: undefined method `+' for #<User:0x00000007d7d528>
    from /home/augustin/.rvm/gems/ruby-2.1.4/gems/activemodel-3.2.21/lib/active_model/attribute_methods.rb:407:in `method_missing'
    from /home/augustin/.rvm/gems/ruby-2.1.4/gems/activerecord-3.2.21/lib/active_record/attribute_methods.rb:149:in `method_missing'
    from /home/augustin/.rvm/gems/ruby-2.1.4/gems/activesupport-3.2.21/lib/active_support/core_ext/array/access.rb:19:in `to'
    from /home/augustin/.rvm/gems/ruby-2.1.4/gems/activerecord-3.2.21/lib/active_record/associations/collection_proxy.rb:91:in `method_missing'
    from (irb):14
    from /home/augustin/.rvm/gems/ruby-2.1.4/gems/railties-3.2.21/lib/rails/commands/console.rb:47:in `start'
    from /home/augustin/.rvm/gems/ruby-2.1.4/gems/railties-3.2.21/lib/rails/commands/console.rb:8:in `start'
    from /home/augustin/.rvm/gems/ruby-2.1.4/gems/railties-3.2.21/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:40:in `require'
    from script/rails:40:in `<main>'

And the craziest thing is that:

User.first.transactions.active.owner(User.first)

Works!!

I'm using Rails 3.2 so pretty old I know, but still, annoying, right?

Questions are:

  • Shouldn't User.first.transactions.class be an ActiveRecord::Relation?
  • Why does the error occurs at User.first.transactions.owner(User.first)? Is it an ActiveRecord bug or am I doing something wrong?

Display 404 error document for invalid urls from apache without hitting rails application

Is it possible to show 404.html error document for invalid URLs using RewriteRule from Apache before it hits Rails application.

We have routes like /website/stats_for_season/1031475/23 in our application. But for some reason google bot is accessing URLs like /website/stats_for_season/1031475 without last part.

I have added below rule to Apache .conf file, without success.

RewriteRule ^website/stats_for_season/([0-9]+)/$ '' [R=404] [L]

How to export models to a CSV file using Rails 3?

I'd like to export all database entries into a csv using Rails 3.2. I've been following these instructions:

My controller:

...
elsif params[:reference] == 'exportnews'
  @data = News.find(:all, :order => "date_posted desc", :conditions => "#{Settings.show} = 1", :limit => "5")
  respond_to do |format|
    format.html { redirect_to root_url }
    format.csv { send_data @data.to_csv }
  end
else
...

My model:

  class News < ActiveRecord::Base
      attr_accessible :content, :date_posted, :heading, :hidden, :reference, :title, :user
      def self.to_csv(options = {})
          CSV.generate(options) do |csv|
            csv << column_names
            all.each do |product|
              csv << product.attributes.values_at(*column_names)
            end
          end
        end
    end

yet when I visit the specified url (I've created a route in config/routes.rb I get a csv file with the following details:

#<News:0x007fef657d69f8> #<News:0x007fef632b95a8> #<News:0x007fef632b8ec8> #<News:0x007fef632b8680> #<News:0x007fef632b7e38>

What am I missing?

Generic Module in rails

I have all common function in a module Helper. Those function will work only if it include a constants file which is dynamic based on every project. Now, what is the best approach to reuse the module?

module Helper
  #dunno how to include the constants file and reuse it
  def morning_food(who)
   puts FOOD_HABIT[:morning]
  end
end

../Constant files

module Animal
 module Constants
 FOOD_HABIT = {
  morning: "a",
  ...
 }
 end
end

module Person
 module Constants
 FOOD_HABIT = {
  morning: "dosa",
  ...
 }
 end
end

How to get the value enetered in custom field in custom workflow

I'm new to redmine. I want to get the value from one custom field and set it to other. So how can I get the value of custom field in custom workflow.

rails with devise, How to seperate login view of front and back

I'm try to seperate login view between front and back, I'm create devise user model and admin model inherit user.

../model/user.rb

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

../model/admin.rb

class Admin < User
end

and I duplicate every view folder in users to admin folder(sessions, users, etc..).

It's work to login page front and back, But before_action :autenticate_(admin or user) are seperate front and back. I can't be used together data after login in front and backend.

So the question is: How to used user data after login between front and backend?

Sorry my english is not good.

mercredi 24 juin 2015

Rails 3.2 - best_in_place editing - Date value format issue while editing

In my Rails 3.2 web application, I have used best_in_place gem to create a basic resume template. I have an issue with the the type :date. By default it is showing date in the yyyy-mm-dd format, but I need mm/dd/yyyy format both when displaying and editing. For changing the format in display, I have used a helper display_as: in best_in_place and I could see that the format has been changed.

The problem is that when I click on the value to edit it, it will again go back to the old format (yyyy-mm-dd), Please help me fixing this issue. Below you can find the code for it.

View

<div id="resume_template">
    <div id="user_personal_info" class="sub_template" align="center">
        <div class="title_section"><b>PERSONAL PROFILE</b></div>
        <hr>
        <table width="100%">
            <tr>
                <td valign="middle"align="right" width="35%">NAME</td>
                <td valign="middle"width="10%" class="colon_td">:</td>
                <td valign="middle"width="55%"><%= get_user_content('name') %></td>
            </tr>
            <tr>
                <td valign="middle"align="right" width="35%">EMAIL</td>
                <td valign="middle"width="10%" class="colon_td">:</td>
                <td valign="middle"width="55%"><%= get_user_content('email') %></td>
            </tr>
            <tr>
                <td valign="middle"align="right" width="35%">DATE OF BIRTH</td>
                <td valign="middle"width="10%" class="colon_td">:</td>
                <td valign="middle"width="55%"><%= best_in_place @resume, :dob, url: resume_path(@resume), type: :date, display_as: :format_dob %></td>
            </tr>
            <tr>
                <td valign="middle"align="right" width="35%">GENDER</td>
                <td valign="middle"width="10%" class="colon_td">:</td>
                <td valign="middle"width="55%"><%= best_in_place @resume, :gender, type: :select, collection: [[0, 'Male'], [1, "Female"]], value: @resume.gender %></td>
            </tr>
            <tr>
                <td valign="middle"align="right" width="35%">MARITAL STATUS</td>
                <td valign="middle"width="10%" class="colon_td">:</td>
                <td valign="middle"width="55%"><%= best_in_place @resume, :marital_status, type: :select, collection: [[0, 'Single'], [1, "Married"]] %></td>
            </tr>
            <tr>
                <td valign="middle"align="right" width="35%">LINGUISTIC ABILITY</td>
                <td valign="middle"width="10%" class="colon_td">:</td>
                <td valign="middle"width="55%"><%= best_in_place @resume, :linguistic_ability %></td>
            </tr>
            <tr>
                <td valign="middle"align="right" width="35%">NATIONALITY</td>
                <td valign="middle"width="10%" class="colon_td">:</td>
                <td valign="middle"width="55%"><%= best_in_place @resume, :nationality %></td>
            </tr>
        </table>
    </div>

    <div id="user_education_info" class="sub_template" >
        <div class="title_section"><b>EDUCATIONAL BACK GROUND/QUALIFICATION</b></div>
        <hr>
        <%= best_in_place @resume, :educational_info, type: :textarea %>
    </div>

    <div id="user_prof_exp_info" class="sub_template" >
        <div class="title_section"><b>WORK EXPERIENCE</b></div>
        <hr>
        <%= best_in_place @resume, :work_experience_info, type: :textarea %>
    </div>

    <div id="user_certification_info" class="sub_template" >
        <div class="title_section"><b>CERTIFICATION</b></div>
        <hr>
        <%= best_in_place @resume, :certification_info, type: :textarea %>
    </div>
</div>

<script type="text/javascript">
    $( document ).ready( function (){
        // $.extend($.fn.datepicker.defaults, { format: 'mm/dd/yy' });
        /* $.datepicker.setDefaults({
            dateFormat: 'mm/dd/yy'
        });*/

        jQuery(".best_in_place").best_in_place();
    });
</script>

Model

class Resume < ActiveRecord::Base
  belongs_to :user
  attr_accessible :certification_info, :dob, :educational_info, :gender, :linguistic_ability, :marital_status, :nationality, :work_experience_info

  def format_dob
    self.dob.strftime("%m/%d/%Y")
  end
end

Attached two screenshots for reference. If it can't bee seen, please download and zoom the picture. Thank for any help :) enter image description here

Fetch value from Redmine Custom Custom field

I have created custom field in redmine wher we type the client phone number manually.Also written a ruby code in redmine custom workflow to send sms to client when ticket id is raised.In the code I can type phone number but i actually want to fetch that phone number which we type before creating the new issue..So how do i fetch the value of phone number from the custom field and link it to the code? Please suggest me

Render partial along with another object

This is my controller method:

def update
  @properties = Property.all
  @user = User.all

  respond_to do |format|
    format.js { render partial: 'property_all' }
  end
end

While rendering partial, can I also render another object something like below which can be captured in AJAX request?

format.js { render partial: 'property_all', user: @user } 

AJAX:

success : function (response, object) {
}

ActiveRecord Create ignores value

I am doing this

CasPgtiou.create({:pgt_iou => "a", :pgt_id => "b"})

which results in

    INSERT INTO `cas_pgtious` (`created_at`, `pgt_id`, `pgt_iou`, `updated_at`) VALUES ('2015-06-25 02:22:55', NULL, NULL, '2015-06-25 02:22:55')
            Mysql2::Error: Column 'pgt_id' cannot be null: INSERT INTO `cas_pgtious` (`created_at`, `pgt_id`, `pgt_iou`, `updated_at`) VALUES ('2015-06-25 02:22:55', NULL, NULL, '2015-06-25 02:22:55')
ActiveRecord::StatementInvalid: Mysql2::Error: Column 'pgt_id' cannot be null: INSERT INTO `cas_pgtious` (`created_at`, `pgt_id`, `pgt_iou`, `updated_at`) VALUES ('2015-06-25 02:22:55', NULL, NULL, '2015-06-25 02:22:55')

Even though the value is there the create function is not taking it. Also the model I have is like this

class CasPgtiou < ActiveRecord::Base
        attr_accessible :pgt_iou, :pgt_id
end

Rails version is 3.1.3. I'm not sure why a thing as simple as this would fail.

PS I have tried create this way also. But same error

CasPgtiou.create(:pgt_iou => "a", :pgt_id => "b")

UPDATE

This thing strangely works

pgtiou = CasPgtiou.new
          pgtiou[:pgt_iou] = pgt_iou
          pgtiou[:pgt_id] = pgt
          pgtiou.save!

How to put specific options on top of dropdown list in rails

I need to show some specific options in a dropdown list on top and should sort other options in alpha order. For example if the list is,

["CANADA", "PORTUGAL", "AUSTRALIA", "USA", "BRAZIL"]

I need to show the dropdown list as (usa and portugal as per requirements on top of the list and others in alpha order.)

["USA", "PORTUGAL", "AUSTRALIA", "BRAZIL", "CANADA"]

Ruby on Rails - delegate devise member on has_and_belongs_to_many association

I have a has_and_belongs_to_many association between keywords and groups and then a groups belongs_to member association between group and devise.

class Keyword < ActiveRecord::Base
  has_and_belongs_to_many :groups
  delegate :member, to: :groups
  validate :keywords_within_limit, on: :create

  def keywords_within_limit
    if self.member.keywords(:reload).count >= self.member.keyword_limit
       errors.add(:keyword, "exceeded limit")
    end
  end
end

Im trying access my members methods using delegate but I am getting the error NoMethodError - undefined method member for #<ActiveRecord::Associations::CollectionProxy []>:

Why can't I access my members methods using delegate?

Twitter Bootstrap in Rails

I generated views using this command

rails g bootstrap:themed Todo

it generated several views for my model.

I am using git and reverted the project to its former branch without the boostrap.

Now, I am trying to regenerate the views but it always returns this

   identical  app/views/manifests/index.html.erb

How do I force the bootstap generator to regenerate the views for my project?

TIA

rails 3 link_to put method not working

I am using link_to helper and trying to set the method as :put as show in the documentation. Link

however when i see the method is falling back to get, what am i doing wrong. Here is my syntax

<%= link_to "Original One","/users/#{user.id}?params=#{session[:user]}", :remote => true,:method => :put %>

syntax error: unexpected keyword_ensure, expecting ')' unexpected keyword_end, expecting ')'

Am using the collection_select command of RoR to make a drop down menu calling from another table. But am failing to make it call two columns(i.e first_name and last_name) in my drop down menu. Any body who can help me with the collection_select syntax?

How can I make sure actionmailer & mail gems are only loaded when needed?

I'm trying to reduce my rails 3.2.22 app's memory usage and read that the mail gem eats memory like it's a buffet (http://ift.tt/1ATwCQT). This page says to upgrade mail gem to 2.6.3, but actionmailer 3.2.22 seems to be incompatible with that version of mail gem.

I only send emails from a few spots in the app and I'm fine moving the actionmailer and mail gems to a specific Gemfile group, but that didn't see to work. I'd prefer not to upgrade to rails 4 yet since that's a much larger task.

What options do I have?

Thanks!

mardi 23 juin 2015

Drop down issue when loading a partial - rails 3

I am working on rails 3 and using ajax to load a form, there is a country drop down that has values thats not loading properly. Its loading html entities of the "<" and ">" sign like "<" & ">".

This is how i am rendering the partial that has the countries list

$j('#insert_to').append("<%= escape_javascript(render :partial => 'verified_address', :locals => { :item => @item, :original_item => nil, :update_alert => false }).html_safe %>");

Any help would be appreciated.

Rails: def create does not add data to table using Rest

I want to add data to table through rest api with url: localhost:3000/api/v1/shoppinglists#create?grocery=fruits

I have created a model already, my controller is located under api/v1/shoppinglists_controller.rb and the code for that is:

shoppinglists_controller.rb:

module Api
    module V1

        class ShoppinglistsController < ApplicationController

            def index
                shop = Shoppinglist.all
                render json: shop.to_json
            end

            def create
                @tst = Shoppinglist.create(grocery: "params[:grocery]")
            end
        end
    end
end

routes.rb:

Rails.application.routes.draw do

  namespace :api do
    namespace :v1 do
      get '/shoppinglists' => 'shoppinglists#index'
      post '/shoppinglists' => 'shoppinglists#create'
    end
  end
end

By default, def index gets triggered but when I do: localhost:3000/api/v1/shoppinglist#create?grocery=fruits then I check on commandline, I still see:

Started GET "/api/v1/shoppinglists" for ::1 at 2015-06-23 23:59:06 -0400
Processing by Api::V1::ShoppinglistsController#index as HTML
  Shoppinglist Load (0.3ms)  SELECT "shoppinglists".* FROM "shoppinglists"
Completed 200 OK in 44ms (Views: 0.2ms | ActiveRecord: 0.4ms)

and my table is empty. I dont understand why still index is getting triggered and how can I make def create to actually insert value in grocery column through rest api.

Rails - uninitialized constant ArticlesController::Article

Please help, not sure what I'm doing wrong at all. I'm just trying to make a simple search form, and I'm guessing I just have an error in my routes maybe, but I'm not that strong at debugging as I'm fairly new.

The error is -

uninitialized constant ArticlesController::Article

routes.rb -

<!DOCTYPE html>
<head>
  <title>Simple Search Form</title>
</head>
<body>
  <!-- When submit the form, the view rendered will be the index view of our articles resource -->
  <%= form_tag(articles_path, :method => "get", class: "navbar-form", id: "search-form") do %>
    <div class="input-append">
      <%= text_field_tag :search, params[:search], class: "span2", placeholder: "Search Articles" %>
      <!-- In order to have the "search" icon int the button, we need to use plain HTML instead 
           of using a Rails form helper -->
      <button class="btn" type="submit"><i class="icon-search"></i></button>
    </div>
  <% end %>
  <%= yield %>
</body>

articles.rb -

def Article < ActiveRecord::Base
  attr_accessible :title, :content

  validates :title, presence: true, uniqueness: true
  validates :content, presence: true

  # It returns the articles whose titles contain one or more words that form the query
  def self.search(query)
    # where(:title, query) -> This would return an exact match of the query
    where("title like ?", "%#{query}%") 
  end
end

articles_controller.rb ***THIS IS WHERE THE ERROR IS**** It highlights "@articles = Article.order("create_at DESC")"

class ArticlesController < ApplicationController
  def index
    if params[:search]
      @articles = Article.search(params[:search]).order("created_at DESC")
    else
      **@articles = Article.order("created_at DESC")**
    end
  end
end

index.html.erb -

    <% @articles.each do |article| %>
  <div class="article">
    <h1 class="article-title"><%= link_to article.title, article %></h1>
    <p class="article-content"><%= article.content %></p>
  </div>
<% end %>

application.html.erb -

<!DOCTYPE html>
<head>
  <title>Simple Search Form</title>
</head>
<body>
  <!-- When submit the form, the view rendered will be the index view of our articles resource -->
  <%= form_tag(articles_path, :method => "get", class: "navbar-form", id: "search-form") do %>
    <div class="input-append">
      <%= text_field_tag :search, params[:search], class: "span2", placeholder: "Search Articles" %>
      <!-- In order to have the "search" icon int the button, we need to use plain HTML instead 
           of using a Rails form helper -->
      <button class="btn" type="submit"><i class="icon-search"></i></button>
    </div>
  <% end %>
  <%= yield %>
</body>

Sorry for all the code, just posting all that I have.

Please let me know how I can assist.

Thanks

Ruby on Rails - Hartl Tutorial Chapter 7 - The action 'index' could not be found for UsersController

I'm new to Ruby on Rails so I'm following Michael Hartl's Ruby on Rails Tutorial and I'm running across an issue.

In Chapter 7 Section 1 you are supposed to be showing User pages but I am running into this error:

"The action 'index' could not be found for UsersController"

when I try to go to "localhost:3000/users"

I'm not sure what all information I would need to include so here is some and please let me know if I need more. I'd greatly appreciate any help I can get. I did look up similar questions on here but none helped me with my issue.

Here is my routes.rb

Rails.application.routes.draw do
root              'static_pages#home'
  get 'help' =>     'static_pages#help'
  get 'about' =>    'static_pages#about'
  get 'contact' =>  'static_pages#contact'
  get 'signup' =>   'users#new'
resources :users
end

users_controller.rb

class UsersController < ApplicationController

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

  def new
  end
end

show.html.erb

<%= @user.name %>, <%= @user.email %>

I've double checked my code against the tutorial and I can't seem to find any difference. The only issue I can think may be when it asked me to create the show.html.erb I just right clicked and hit "create file" in my online IDE (Cloud 9.io which the tutorial recommended). Hartl just says you have to create it by hand so I assume that is what he meant. Again, any help would be greatly appreciated. Thank you.

User login with omniauth on Rails and set anonymous username or alias

I am very new to Rails and before I get deep into the building process, would like to know if anyone knows of a way (or any articles--I've been searching and can't find exactly what I'm looking for) to do the following:

1) have a user login using omniauth 2) after logging in directing the user to set an anonymous username that will what shows for this user throughout the activity in the application (all omniauth use info remains private)

Is there a way to do this? I found this question login using facebook or create an account but I'm essentially having them login using facebook AND set an account of a sorts.

If anyone has any resources that could point me in the right direction, I'd appreciate it!

Ruby on Rails (rake db:seed) - Undefined Attribute Error ___

I'm getting this error, "ActiveRecord: UndefinedAttributeError: Unknown Attribute: name" whenever I try to rake seed.db. I honestly have no idea what's wrong because I defined name in my migration files already.

Here's my code.

Seeds.rb -

 P1 = Post.create(name: "Arsenal")
 P2 = Post.create(name: "Chelsea")

Migration -

   class CreatePosts < ActiveRecord::Migration
      def change
        create_table :posts do |t|
          t.string :name
        end
      end
    end

Let me know if you need anymore files.

Thanks.

Accessing URI params in the controller

(Learning RoR on my own, so pls forgive me if this is an obvious question) I have an app to track books stored on shelves in libraries. A request should come in like:

GET books/library_id   => shows all books on every shelf in a library
GET books/library_id/shelf_id  => shows all books on one shelf in a library
GET books/library_id/shelf_id/book_id  => shows a particular book

POST would use similar formats, except I will be using JSON in the POST body to supply the information (author, pub date, length, etc) for the book, shelf, or library

My question is, [:params] passed in to my controller seems to hold query (anything after a ?) and POST body parameters, but not the URL, which I need to parse and use to determine what to show. Is there a way to get this out of the parameters? I'm trying to avoid something like GET /books/?library_id/shelf_id

Rails 3.2 - Getting Values from User model and saving to Resume Model object on Update

In my Rails 3.2 web application, I have a User, Resume models. For resume, we have set columns like Name, Email, Date of Birth, Nationality, Educational Qualification, Experience etc. My requirement is that after a user is created by ADMIN, the Admin should be able to see a resume template (HTML) where in basic details like Name, Email, Date of Birth etc. would be taken from USER table to display it to the ADMIN for the first time. Then using best_in_place gem, the ADMIN should be able to edit and update all the values except Name and Email (non editable fields) to the RESUME table.

How I should go ahead?

class Resume < ActiveRecord::Base
  belongs_to :user
  attr_accessible :certification_info, :dob, :educational_info, :gender, :linguistic_ability, :marital_status, :nationality, :work_experience_info
end

class User < ActiveRecord::Base
  has_one :resume
  attr_accessible :login, :email, :name, :dob, :gender, :resume_attributes
  accepts_nested_attributes_for :resume
end

How we could associate Resume with User models in routes in this case?

resources :users

Do we need to have a resume_controller here?

How the view could be? Should I set up a form_for for User and then field_for for resume? But I could not use best_in_place, right?

Please suggest a proper solution..

Regular Expression for Email accepting some special characters

I am using following Regular expression for email validation

VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i

Which works perfectly but only one issue is there

.@xyz.com is also consider as Valid email address.

What i need to change in regular expression so that it should check atleast one [a-z] alphabate before @

Is there any gem which can be used to store user log in DB for rails 3.2?

Is there any gem which can be used to store user log ? Following is the list which I want to store:

  • User IP
  • URL which user has hit.
  • Amount of time user is on that page
  • Sign in time
  • Sign out time
  • Total time user has spend in that complete session i.e, time difference between sign in and sign out.

My rails version is 3.2.21. I have checked "Paper trail" and "Public activity" I think first one is helpful for versioning and the later one is one for user news feed. I also checked Fnordmetric but it is used only to track the urls which user had hit. Here I want to store above mentioned list in my log.

I also checked AHOY. I was told it will work properly only on rails4.

Please suggest which one I should use. Thanks in advance.

js alert is calling 2times

I had a problem that I am getting every javascript alert 2times and js calling is also occurring 2 times.

what Can be the root cause?

I checked by git status and there is no file which can be modified and on other system same project is working fine.

Please help me to understand what causing this issue?

Advanced search in active scaffold

I have two models - Benefit and UserBenefit.

Benefit:

:id [integer]
:created_at [datetime]
:expiration_date [datetime]

UserBenefit:

:id [integer]
:user_id [integer]
:benefit_id [integer]
:active [boolean]
:updated_at [datetime]

I would like to create custom search in active scaffold for Benefit model where will be possible to select month and year and list all Benefits which are active in selected time.
Active time of benefit is from created_at to expiration_date.

So far I have created custom method in Benefit model to return all months with year when benefit is active.

  def dates
    d1 = self.created_at
    d2 = self.expiration_date
    m = []
    while d1 <= d2.at_end_of_month
      m << d1.strftime('%b %Y')
      d1 = d1 + 1.month
    end
    m
  end

Then I have created controller for active scaffold:

class Admin::BenefitsController < AdminController
  active_scaffold :benefit do |config|
    config.columns = :id, :expiration_date, :created_at, :dates
    config.actions = [:list, :field_search, :export, :show, :update, :create]
    config.field_search.columns = :dates
    config.list.per_page = 50
  end
end

and helper for search:

module BenefitHelper
  def benefit_dates_search_column(record, input_name)
    select :record, :dates, options_for_select(Date::ABBR_MONTHNAMES.compact.each_with_index.collect{|m, i| [m, i+1]}), {:include_blank => as_(:_select_)}, input_name
  end
end

There is a moment when problems begins. This select doesn't appear in search and the second thing is that I have no idea how to add year selection.

After this I would like also to list how many Users where active in selected benefits.
Active users - UserBenefit.updated_at - equals to selected date and UserBenefit.active = true

There is the last problem. There is an easy way to add additional column which will count all active users for each Benefit, but how can I update it depending on selected date in search?

lundi 22 juin 2015

Kaminari Link modification in Rails 4

Using kaminari , i currently generate link something like below

http://localhost:3000/San-Jose_CA?page=52&pgsz=20

But how can i restructure it like below

http://localhost:3000/San-Jose_CA/pg-52?pgsz=20

String concatenation of two attributes in Rails where query

Let's say I have the attrs first_name and last_name for a User. I know the user's full name is "Johnny Appleseed", as I have a large Hash of user's full names as strings.

Sure, I could split each string first, and search like so: User.where(first_name: 'Johnny', last_name: "Appleseed")

BUT, I'm wondering if there is a way to basically concat the two in a query, essentially like so: User.where('first_name + last_name = ?', 'Johnny Appleseed')

Or if I could have a full_name method on the User model, and search by that?

 def full_name
    "#{self.first_name} #{self.last_name}"
  end

User.where('full_name = ?', 'Johnny Appleseed')