Tuesday, April 26, 2016

Use decorator in rabl | Fixed issues

Use decorator in rabl | Fixed issues


Use decorator in rabl

Posted: 26 Apr 2016 07:02 AM PDT

does any know how to use decorator in rabl file ?

collection @invitations    child(:user)     attributes ....  

I wonder to be able to do

collection @invitations    child(:user => user.decorate)     attributes ....      object false  child UserDecorator.decorate(current_user)  

is allow but I can't figure out the right syntaxe for my problem

How to implement a short version of the same contact form in a rails app?

Posted: 26 Apr 2016 07:01 AM PDT

I'm not sure if I worded that title correctly, but I want to have a short version of my contact form on my index page. The problem is that the shorter version is still expecting the same validations as the long version, and it redirects to the contacts/new path when there are errors. How would I handle a situation like this; because this short contact form requires different behavior than the long version, would I have to somehow make a different contact form all together? Any help or suggestions on how to do this would be greatly appreciated.

Short:
This is in the root page

    <%= simple_form_for @contact, :html => {:class => 'form-horizontal' } do |f| %>        <div class="form-group">          <div class="control-label col-sm-3">            <%= f.label :firstName, 'Name' %>          </div>          <div class="col-sm-6">            <%= f.input_field :firstName, class: "form-control", placeholder: "Name" %><br/>          </div>        </div>          <div class="form-group">          <div class="control-label col-sm-3">            <%= f.label :email, 'Email' %><br/>          </div>          <div class="col-sm-6">            <%= f.email_field :email, class: "form-control", placeholder: "Email" %><br/>          </div>        </div>          <div class="form-group">          <div class="control-label col-sm-3">            <%= f.label :phoneNumber, 'Phone' %>          </div>          <div class="col-sm-6">            <%= f.input_field :phoneNumber, class: "form-control", placeholder: "Phone" %><br/>          </div>        </div>          <div class="form-group">          <div class="col-sm-6 col-sm-offset-3">            <%= f.button :submit, 'Submit Request', :class=> "btn btn-primary" %>          </div>        </div>      <% end %>  

Model

    class Contact < MailForm::Base    validates_presence_of :firstName, :lastName, :email, :budget, :message => "Can't Be Blank"      attribute :firstName    validates_format_of :firstName, :with => /\A([a-z]|[A-Z])/i      attribute :lastName    validates_format_of :lastName, :with => /\A([a-z]|[A-Z])/i      attribute :company    validates_format_of :company, :with => /\A([a-z]|[A-Z])/i,                                  :allow_blank => true      attribute :email    validates_format_of :email, :with => /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i,                                :message => "Invalid Format"      attribute :phoneNumber    validates_format_of :phoneNumber, :with => /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/i,                                      :allow_blank => true,                                      :length => { :minimum => 10, :maximum => 31 },                                      :message => "Invalid Format"      attribute :requestedArea, :validate => true    validates_format_of :requestedArea, :with => /\A([a-z]|[A-Z])/i      attribute :requestedState    validates_format_of :requestedState, :with => /\A([a-z]|[A-Z])/i,                                         :allow_blank => true    attribute :requestedCity    validates_format_of :requestedCity, :with => /\A([a-z]|[A-Z])/i,                                        :allow_blank => true    attribute :contactMethod    attribute :budget, :validate => true    attribute :numberOfRooms      attribute :numberOfOccupants    attribute :purpose    attribute :pets    attribute :petType    attribute :numberOfPets    attribute :arrivalDate      attribute :departureDate    validates_format_of :departureDate, :with => /\d{2}\/\d{2}\/\d{4}/i,                                        :allow_blank => true    def headers      {        :subject => "Quote Requested!",        :to => "anthonydevenuto@gmail.com",        :from => %(#{email})      }    end  end  

Controller

class ContactsController < ApplicationController    def new      @contact = Contact.new    end    def create      @contact = Contact.new(params[:contact])      # @contact.request = request      if @contact.deliver        flash[:notice] = 'Thank you for your request. We will contact you soon!'        redirect_to root_path      else        flash.now[:error] = 'Cannot send message.'        render :new      end    end  end  

a good numberical captcha on ROR

Posted: 26 Apr 2016 07:04 AM PDT

I want a strong and simple captcha for my rails app . I used re-captcha gem but it have a second verifying that " select all pics with ... " .

So i used Simple-captcha-mirror that needs image-magick , but it use many RAM memory and i dont like that . So i also tried Negative-captcha , Brain buster , ... but they are not good in my mind.

I want to know can i create a simple and strong captcha are is another good captcha ?

Using active admin I want to be able to display uploaded image names and delete them

Posted: 26 Apr 2016 06:38 AM PDT

I am using activeadmin with carrierwave for uploads. I have a has_one relationship between groups and their logos. For this reason I can't use activeadmin's has_many feature with the f.inputs method. So I separated it as so:

f.inputs 'Group Logo', allow_destroy: true, for: [:avatar, f.object.avatar || Avatar.new] do |avatar_form|    avatar_form.input :file, hint: f.object.try(:logo_image_url)    avatar_form.input :_destroy, :as=>:boolean, :required => false, :label => 'Remove Logo'  end  

However the remove is a checkbox. The behavior that I want is for the form to show the image name if one is present and if the user clicks "Remove Logo" i want the name to disappear and no association to be there after save. Otherwise i just want the user to be able to add, change, or do nothing to the logo.

Refile--Dropzone-like div, hide file input

Posted: 26 Apr 2016 06:35 AM PDT

Using the rails refile gem, is it possible to hide the attachment_field and add a dropzone.js-like div that will add a file to the attachment_field when dropped?

Refile is amazing, and I'm happy to use as-is, but would love to have a dropzone-like div that I could make some pretty UI for.

PG::UndefinedColumn: ERROR: column "courseid" of relation "courses" does not exist

Posted: 26 Apr 2016 06:38 AM PDT

I am doing Rails + PostgreSql app. I need to run sql dump on production env. I have courses table with courseID attribute. But when I run my sql I get this error:

PG::UndefinedColumn: ERROR:  column "courseid" of relation "courses" does not exist  LINE 1: INSERT INTO courses (courseID, name, created_at, updated_at)...

Here is how my sql dump looks like:

INSERT INTO course (courseID, name, created_at, updated_at) VALUES  ('CSCI150', 'Fundamentals of Programming',  localtimestamp, localtimestamp ),  etc...;

Tried to put quotes (' ') around attributes, didn't help. Strange error. What might cause that? EDIT: Here is what in my schema.rb

  create_table "courses", force: :cascade do |t|      t.string   "name"      t.string   "courseID"      t.integer  "school_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end

how to avoid Nill class for this

Posted: 26 Apr 2016 06:54 AM PDT

I'm getting entity_name is nill class for this

<%= f.text_field :transferred_entity_id ,id: "transferred_entity_id", :value => @employee.entity_name,class: "form-control"%>  

This is the code I'm having. Can any tell me how to avoid nil class for this using the down code

<%= f.text_field :transferred_entity_id ,id: "transferred_entity_id", :value =>  @employee.other_entity.entity_name.present? ? @employee.other_entity.entity_name : [nil],class: "form-control" %>  

while im editing im rendering to another page i need to do hardcode for this, using terminal operator condition then only it will work can any one suggest me how to do

Is there a way to create a Rails resource route called `index`?

Posted: 26 Apr 2016 06:34 AM PDT

I want to add a resource route called index to a Rails 4 application but the generated routes aren't as expected. However, if I use another name (such as show_index), they are. To demonstrate, I'll begin with a vanilla Rails app that has no routes:

$ rake routes  You don't have any routes defined!  

I add the below into config/routes.rb:

  resources :items  

Which produces the following resourceful Rails routes:

   Prefix Verb   URI Pattern               Controller#Action      items GET    /items(.:format)          items#index            POST   /items(.:format)          items#create   new_item GET    /items/new(.:format)      items#new  edit_item GET    /items/:id/edit(.:format) items#edit       item GET    /items/:id(.:format)      items#show            PATCH  /items/:id(.:format)      items#update            PUT    /items/:id(.:format)      items#update            DELETE /items/:id(.:format)      items#destroy  

The application has a show action that can render a so-called index if the parameter hash contains {with: 'index'} (this index is an application-specific thing, rather than a collection of items or anything like that).

I add a custom index route to invoke the show action with the additional parameter:

  resources :items do      get 'index' => 'items#show', with: 'index'    end  

This produces a new route but it has item_id instead of the expected id (compare with edit_item in the list above):

item_index GET    /items/:item_id/index(.:format) items#show {:with=>"index"}  

The Routing documentation explains that the way to get :id is to use on: :member, so the route would need to be

get 'index' => 'items#show', with: 'index', on: :member  

but that doesn't produce the expected results. It adds the expected route but it steals the item method prefix from the default show action instead of using its own index_item (again, compare with edit_item in the list above):

item GET    /items/:id/index(.:format) items#show {:with=>"index"}       GET    /items/:id(.:format)       items#show  

However, had I used something other than index, such as show_index, then it would work as expected:

get 'show_index' => 'items#show', with: 'index', on: :member  

produces

show_index_item GET    /items/:id/show_index(.:format) items#show {:with=>"index"}  

So there is a difference in behaviour when the route is called index. I expect this is because the implied resources routes use that name, although I don't think they use it in a way that would clash. It looks to me like I should be able to add a new index route which would become index_item (similar to the exisitng edit_item and in contrast to the existing item_index).

I know I can work around the problem, as I have demonstrated, by using a different name. But index reads better than show_index.

So my question asks is it possible to specify a resource route with index that is keyed off :id ? `

What is is Engine in Ruby On Rails

Posted: 26 Apr 2016 06:57 AM PDT

I read now rails tutorial about Engine. I cant undestand what is this Engine. In tutorial describe: Engines can be considered miniature applications that provide functionality to their host applications.

Who can explain more clear, what is Engine?

Dynamically showing profile user name in 'from' email field using rails

Posted: 26 Apr 2016 06:27 AM PDT

We're currently building a web-based application that allows users to sign up and create a profile. They can send emails from the platform using actionmailer but instead of showing a default 'no-reply' as the from field we need to show the sender's name. Does anyone know if this is possible?

capistrano: cp - cannot stat

Posted: 26 Apr 2016 05:49 AM PDT

I'm trying to deploy errbit (https://github.com/errbit/errbit), and can't get capistrano to compile the assets on a remote server. It appears it's adding for no good reason some gibberish when it creates the manifest path, and I really have no idea where to watch to fix it...

Here is the Capistrano output

  01 /usr/local/rvm/bin/rvm 2.3.0 do bundle exec rake assets:precompile    01 Notice: no rspec tasks available in this environment    01 Overwriting existing field _id in class App.    01 Creating scope :page. Overwriting existing method NotificationServices…  ✔ 01 deployer@000.000.000.000 2.336s    00:22 deploy:assets:backup_manifest    01 mkdir -p /home/deployer/apps/errbit/releases/20160426123255/assets_man…    01  ✔ 01 deployer@000.000.000.000 0.330s /home/deployer/apps/errbit/releases/20160…    02    02 cp: cannot stat '\033[?25h\033[0G\033[K\033[?25h\033[0G\033[K/home...    02 : No such file or directory    (Backtrace restricted to imported tasks)    cap aborted!    SSHKit::Runner::ExecuteError: Exception while executing as deployer@000.000.000.000: cp exit status: 1    cp: cannot stat '\033[?25h\033[0G\033[K\033[?25h\033[0G\033[K/home/deployer/apps/errbit/releases/20160426123255/public/assets/.sprockets-manifest-cd1becb3ebe39b1efd086cd82910b5dd.json': No such file or directory    cp stderr: Nothing written      SSHKit::Command::Failed: cp exit status: 1    cp: cannot stat '\033[?25h\033[0G\033[K\033[?25h\033[0G\033[K/home/deployer/apps/errbit/releases/20160426123255/public/assets/.sprockets-manifest-cd1becb3ebe39b1efd086cd82910b5dd.json': No such file or directory    cp stderr: Nothing written      Tasks: TOP => deploy:assets:backup_manifest    (See full trace by running task with --trace)    The deploy has failed with an error: Exception while executing as deployer@000.000.000.000: cp exit status: 1    cp: cannot stat '\033[?25h\033[0G\033[K\033[?25h\033[0G\033[K/home/deployer/apps/errbit/releases/20160426123255/public/assets/.sprockets-manifest-cd1becb3ebe39b1efd086cd82910b5dd.json': No such file or directory    cp stderr: Nothing written  

As you can see before /home/deployer there are some randomcharacters I'm not able to understand.

The only place I think could have something to do is the deploy_to instruction:

set :deploy_to, '/home/deployer/apps/errbit'  

Here is my Gemfile.lock

https://gist.github.com/ngw/1157a005ff7f6077b9f5b232b0371a76  

I'm not able to see the problem here.

Can someone help me?

ArgumentError: The provided regular expression is using multiline anchors (^ or $)

Posted: 26 Apr 2016 06:06 AM PDT

I have added password restrictions to my code. after that i am getting an error of:

ArgumentError: The provided regular expression is using multiline anchors (^ or $), which may present a security risk. Did you mean to use \A and \z, or forgot to add the :multiline => true option?  

My user.rb file is

validates :password, :format => {:with => /^(?=.*[a-zA-Z])(?=.*[0-9]).{6,}$/}  

Table historic with all the authorizations ids checked update column

Posted: 26 Apr 2016 05:42 AM PDT

I have this problem... I need save my table historic with all the authorizations ids checked, update the column authorization_origin_id and set the column refinancing_id with the refinancing id created. Example: I checked authorizations ids 2 and 3, so I create historic with two lines with authorization_origin_id 2 and 3 and the refinancing id will be 1. My code:

My view this it:

<%= simple_form_for(@refinancing) do |f| %>        <div class="form-inputs">          <%= f.hidden_field :employee_id, value: @employee.first.id %>          <%= f.hidden_field :authorization, value: @authorization  %>          <%= f.input :contract_number %>        </div>          <h3>Reserved value</h3>        <table class="table table-condensed table-bordered table-striped">          <thead>            <th>Authorization id</th>            <th>Contract number</th>          </thead>          <% @authorizations.each do |authorization| %>            <tbody>              <tr>                <td><%= authorization.id %></td>                <td><%= authorization.contract_number %></td>              </tr>            </tbody>          <% end %>        </table>          <div class="form-actions">          <%= f.button :submit, "To Reserve" %>        </div>      <% end %>  

Controller is this:

 def new          if params[:authorization].present?            @selected_ids = params[:authorization][:contract_number]            @authorizations = Authorization.where("contract_number in (?)", @selected_ids)            auth_params = params[:authorization]            auth_params[:contract_number].zip(auth_params[:value_solve].reject(&:blank?)).each do |contract_number, value_solve|                Authorization.where(contract_number: contract_number).update_all(value_solve: value_solve, situation: 2)            end              @authorizations.ids.each do |auth_id|              @historic_refinancing = HistoricRefinancing.create              @historic_refinancing = HistoricRefinancing.update_all(authorization_origin_id: auth_id)            end            end          @employee = Employee.search_cpf(params[:search_employee_by_cpf])          @refinancing = Refinancing.new          end  

Actually my table historic is wrong, authorization_origin_id take, just the last (just one ever =/) value checked and refinancing_id is null

Issues installing gems due to ruby versions

Posted: 26 Apr 2016 05:47 AM PDT

I've installed rails and ruby using homebrew and following a break from coding, have recently attempted to upgrade my packages.

When running:

bundle install --without production  

I receive the following error message:

Gem::InstallError: listen requires Ruby version ~> 2.2.  An error occurred while installing listen (3.1.1), and Bundler cannot     continue.  Make sure that `gem install listen -v '3.1.1'` succeeds before bundling.  

Checking via brew update, I have ruby 2.3 so am unclear why this will not install.

Additionally, when I try to check my rails version, I receive the following error.

Could not find gem 'rails_12factor (= 0.0.2) ruby' in the gems available on this machine.  

I'd appreciate a recommendation of a good tutorial to enable me to go back through the update process or a quick fix?

Thank you

Sunspot - RSolr::Error::Http - 404 Not Found

Posted: 26 Apr 2016 07:06 AM PDT

Hi I recently got a hold of a Rails 3.2.0 project that makes use of sunspot

I've been running into an error below:

RSolr::Error::Http - 404 Not Found  Error:     Not Found    URI: http://localhost:8982/solr/select?wt=ruby  Request Headers: {"Content-Type"=>"application/x-www-form-urlencoded; charset=UTF-8"}  Request Data: "fq=type%3APost&fq=-kind_s%3A%28event+OR+contest+OR+job+OR+review%29&fq=-category_im%3A%28%29&fq=exclude_from_explore_b%3Afalse&fq=-destroyed_at_d%3A%5B*+TO+*%5D&fq=published_at_ds%3A%5B*+TO+2016%5C-04%5C-26T12%5C%3A07%5C%3A29Z%5D&fq=published_at_ds%3A%5B*+TO+*%5D&fq=verified_author_b%3Atrue&sort=published_at_ds+desc&start=0&rows=24&q=*%3A*"    Backtrace: /home/revrun/.rvm/gems/ruby-2.1.2/gems/rsolr-1.0.13/lib/rsolr/client.rb:284:in `adapt_response'  /home/revrun/.rvm/gems/ruby-2.1.2/gems/rsolr-1.0.13/lib/rsolr/client.rb:190:in `execute'  /home/revrun/.rvm/gems/ruby-2.1.2/gems/rsolr-1.0.13/lib/rsolr/client.rb:176:in `send_and_receive'  (eval):2:in `post'  /home/revrun/.rvm/gems/ruby-2.1.2/gems/sunspot-1.3.3/lib/sunspot/search/abstract_search.rb:38:in `execute'  /home/revrun/.rvm/gems/ruby-2.1.2/gems/sunspot_rails-1.3.3/lib/sunspot/rails/searchable.rb:329:in `solr_execute_search'  /home/revrun/.rvm/gems/ruby-2.1.2/gems/sunspot_rails-1.3.3/lib/sunspot/rails/searchable.rb:153:in `solr_search'  /home/revrun/Code/saf/safarious/app/controllers/explore/posts_controller.rb:76:in `post_search'  /home/revrun/Code/saf/safarious/app/controllers/explore/posts_controller.rb:15:in `category'  /home/revrun/.rvm/gems/ruby-2.1.2/gems/actionpack-3.2.13/lib/action_controller/metal/implicit_render.rb:4:in `send_action'  /home/revrun/.rvm/gems/ruby-2.1.2/gems/actionpack-3.2.13/lib/abstract_controller/base.rb:167:in `process_action'  

My installed gems are as follows:

*** LOCAL GEMS ***    actionmailer (4.2.6, 4.1.0, 3.2.13)  actionpack (4.2.6, 4.1.0, 3.2.13)  actionview (4.2.6, 4.1.0)  activejob (4.2.6)  activemodel (4.2.6, 4.1.0, 3.2.13)  activerecord (4.2.6, 4.1.0, 3.2.13)  activeresource (3.2.13)  activesupport (4.2.6, 4.1.0, 3.2.13)  acts-as-taggable-on (2.3.3)  acts_as_votable (0.8.0)  addressable (2.4.0, 2.3.6, 2.3.2)  afm (0.2.0)  annotate (2.5.0)  arel (6.0.3, 5.0.1.20140414130214, 3.0.2)  Ascii85 (1.0.2)  authlogic (3.2.0)  autoprefixer-rails (6.3.6)  awesome_print (1.6.1, 1.1.0)  base58 (0.1.0)  bcrypt (3.1.7)  bcrypt-ruby (3.0.1)  bigdecimal (1.2.4)  binding_of_caller (0.7.2)  bootstrap (4.0.0.alpha3)  bootstrap-sass (3.1.1.1, 3.1.1.0)  bourbon (3.0.1)  braintree (2.22.0)  browser (0.1.6)  bson (3.2.6)  builder (3.2.2, 3.0.4)  bundler (1.8.3)  bundler-unload (1.0.2)  byebug (8.2.2)  callsite (0.0.11)  cancan (1.6.10)  capistrano (3.2.1)  capistrano-bundler (1.1.2)  capistrano-rails (1.1.1)  capistrano-rvm (0.1.1)  capybara (2.3.0, 2.0.2)  carmen (0.2.13)  carrierwave (0.8.0)  carrierwave_backgrounder (0.1.3)  childprocess (0.5.3, 0.3.6)  chronic (0.10.2)  client_side_validations (3.2.1)  client_side_validations-simple_form (2.0.1)  coderay (1.1.1)  coffee-rails (4.1.1, 4.0.0, 3.2.2)  coffee-script (2.4.1, 2.3.0)  coffee-script-source (1.10.0, 1.8.0)  colorize (0.7.3)  commonjs (0.2.7)  concurrent-ruby (1.0.1)  connection_pool (2.2.0)  cookiejar (0.3.0)  crack (0.4.2, 0.3.2)  daemons (1.2.3, 1.1.9)  dante-editor (0.0.14)  database_cleaner (1.3.0, 0.9.1)  debug_inspector (0.0.2)  declarative_authorization (0.5.7)  delayed_job (4.1.1, 3.0.4)  delayed_job_active_record (0.3.3)  delayed_job_mongoid (2.2.0)  diff-lcs (1.2.5, 1.1.3)  domain_name (0.5.20160309)  dotenv (0.9.0)  dotenv-rails (0.9.0)  em-http-request (1.1.3)  em-socksify (0.3.1)  email_validator (1.4.0)  erubis (2.7.0)  eventmachine (1.2.0.1, 1.0.3)  exceptional (2.0.33)  excon (0.49.0, 0.16.10)  execjs (2.6.0, 2.2.1, 1.4.0)  executable-hooks (1.3.2)  factory_girl (4.4.0, 4.1.0)  factory_girl_rails (4.4.1, 4.1.0)  fakeredis (0.4.1)  faraday (0.9.2, 0.9.0, 0.8.11, 0.7.6)  faraday_middleware (0.10.0, 0.9.0)  fattr (2.2.1)  faye (1.1.2)  faye-websocket (0.10.3)  ffi (1.9.3, 1.3.1)  filepicker-rails (0.1)  fog (1.9.0)  foreman (0.78.0)  formatador (0.2.4)  garb (0.9.1)  gem-wrappers (1.2.7)  globalid (0.3.6)  god (0.13.7)  haml (4.0.7)  haml-rails (0.9.0)  handlebars_assets (0.19.1)  hashdiff (0.3.0)  hashery (2.1.0)  hashie (3.4.3, 1.2.0)  heroku (3.43.0)  heroku-api (0.4.2)  highline (1.7.8, 1.6.15)  hike (1.2.3, 1.2.2)  hiredis (0.4.5)  html2haml (2.0.0)  htmlentities (4.3.1)  http-cookie (1.0.2)  http_parser.rb (0.6.0)  httpauth (0.2.0)  i18n (0.7.0, 0.6.11, 0.6.1)  io-console (0.4.2)  jbuilder (2.4.1, 1.5.3)  journey (1.0.4)  jquery-rails (4.1.1, 3.1.0, 2.2.0)  jquery-ui-rails (4.2.1)  json (1.8.3, 1.8.1, 1.8.0)  jwt (1.5.1, 1.0.0)  launchy (2.4.3, 2.1.2)  less (2.6.0)  less-rails (2.7.1)  letter_opener (1.0.0)  libv8 (3.16.14.13 x86-linux)  linkedin (0.3.7)  lograge (0.2.0)  loofah (2.0.3)  mail (2.6.3, 2.5.4, 2.5.3)  mail_view (1.0.3)  medium-editor-rails (2.2.0)  meta_request (0.2.5)  method_source (0.8.2)  mime-types (2.99.1, 1.25.1, 1.21)  mini_magick (3.4)  mini_portile (0.6.0)  mini_portile2 (2.0.0)  minitest (5.8.4, 5.3.5, 4.7.5)  mongo (2.1.2)  mongoid (5.1.1)  mongoid-compatibility (0.3.1)  mono_logger (1.1.0)  multi_json (1.11.2, 1.10.1, 1.7.3)  multi_xml (0.5.5)  multipart-post (2.0.0, 1.2.0, 1.1.5)  nesty (1.0.2)  net-scp (1.2.1, 1.0.4)  net-ssh (2.9.2, 2.9.1, 2.6.3)  net-ssh-gateway (1.2.0)  netrc (0.11.0, 0.10.3)  newrelic_rpm (3.6.4.122)  nokogiri (1.6.7.2, 1.6.2.1, 1.5.5)  oauth (0.5.1, 0.4.7)  oauth2 (1.1.0, 0.9.4, 0.6.1)  omniauth (1.3.1, 1.1.1)  omniauth-facebook (3.0.0, 1.4.0)  omniauth-linkedin (0.0.8)  omniauth-oauth (1.0.1)  omniauth-oauth2 (1.4.0, 1.0.2)  omniauth-twitter (0.0.14)  optionable (0.2.0)  options (2.3.2, 2.3.0)  origin (2.2.0)  panda (1.6.0)  pdf-inspector (1.1.0)  pdf-reader (1.3.2)  pg (0.17.1)  polyglot (0.3.5, 0.3.3)  pr_geohash (1.0.0)  prawn (0.12.0)  prawn-qrcode (0.2.0)  prawn_rails (0.0.11)  progress_bar (1.0.5, 0.4.0)  pry (0.10.3)  pry-byebug (3.3.0)  psych (2.0.5)  public_activity (1.5.0)  quiet_assets (1.1.0, 1.0.2)  rack (1.6.4, 1.5.2, 1.4.7, 1.4.5)  rack-cache (1.2)  rack-contrib (1.1.0)  rack-protection (1.5.3)  rack-ssl (1.3.3)  rack-test (0.6.3, 0.6.2)  rails (4.2.6, 4.1.0, 3.2.13)  rails-deprecated_sanitizer (1.0.3)  rails-dom-testing (1.0.7)  rails-html-sanitizer (1.0.3)  rails-sanitize-js (1.0.0)  rails_autolink (1.1.0)  rails_config (0.4.2)  railties (4.2.6, 4.1.0, 3.2.13)  rake (11.1.1, 10.3.2, 10.1.0, 10.0.4)  rdoc (4.1.2, 4.1.0, 3.12.2)  recaptcha (0.3.5)  redis (3.2.2, 3.1.0, 3.0.4)  redis-actionpack (3.2.3)  redis-activesupport (3.2.3)  redis-namespace (1.5.1)  redis-rack (1.4.2)  redis-rails (3.2.3)  redis-store (1.1.4)  ref (2.0.0)  resque (1.25.2)  rest-client (1.8.0, 1.6.9, 1.6.8)  rest-client-components (1.4.0)  rqrcode (0.4.2)  rsolr (1.1.1, 1.0.13, 1.0.10)  rspec-core (2.14.8, 2.12.2)  rspec-expectations (2.14.5, 2.12.1)  rspec-mocks (2.14.6, 2.12.1)  rspec-rails (2.14.0, 2.12.2)  ruby-hmac (0.4.0)  ruby-oembed (0.8.8)  ruby-prof (0.12.1)  ruby-rc4 (0.1.5)  ruby_parser (3.8.1)  rubygems-bundler (1.4.4)  rubyzip (1.1.7, 1.1.6, 0.9.9)  rvm (1.11.3.9)  safe_yaml (1.0.3)  sass (3.4.22, 3.4.21, 3.2.19, 3.2.5)  sass-rails (5.0.4, 4.0.2, 3.2.6)  sdoc (0.4.1)  selenium-webdriver (2.42.0, 2.29.0)  sequel (3.20.0)  sexp_processor (4.7.0)  simple_form (2.0.4)  sinatra (1.4.5, 1.0)  sitemap_generator (4.0.1)  slop (3.6.0)  sorcery (0.8.6)  spring (1.6.4)  sprockets (3.5.2, 2.11.0, 2.2.2)  sprockets-rails (3.0.4, 2.0.1)  sqlite3 (1.3.9)  sshkit (1.5.1)  state_machine (1.1.2)  subexec (0.2.2)  sunspot (1.3.3)  sunspot_rails (1.3.3)  sunspot_solr (2.2.5)  taps (0.3.24)  test-unit (2.1.2.0)  test_after_commit (0.2.0)  therubyracer (0.12.2)  thin (1.6.4, 1.5.1)  thor (0.19.1, 0.18.1)  thread_safe (0.3.5, 0.3.4)  tilt (2.0.2, 1.4.1)  treetop (1.4.15, 1.4.12)  ttfunk (1.0.3)  turbolinks (2.2.3)  typhoeus (0.2.4)  tzinfo (1.2.2, 0.3.37)  uglifier (2.7.2, 1.3.0)  underscore-rails (1.8.3)  unf (0.1.4)  unf_ext (0.0.7.2)  vegas (0.1.11)  web-console (2.3.0)  webmock (1.18.0)  websocket (1.0.7, 1.0.6)  websocket-driver (0.6.3)  websocket-extensions (0.1.2)  whenever (0.9.4)  will_paginate (3.0.4)  xpath (2.0.0, 1.0.0)  yaml_db (0.2.3)  

And my sunspot.yml:

production:    solr:      hostname: localhost      port: 8983      log_level: WARNING    development:    solr:      hostname: localhost      port: 8982      log_level: INFO    test:    solr:      hostname: localhost      port: 8981      log_level: WARNING  

I've tried numerous other suggestions on SO but nothing seems to be fixing the issue. I have no experience with sunspot so indepth answers are most welcome :-D

Thanks.

Name error uninititalized constant when storing controller inside subfolder

Posted: 26 Apr 2016 06:04 AM PDT

The JSON API I am building has a set of routes under the namespace API and V1 (all the routes start with API/V1. I am now creating a new set of controllers and models that are all linked to the "concept" of "association" so I decided to store them in a subfolder "association" inside my folders "controllers" and "models". I also created a new namespace "association" for the routes relative to these controllers.

I have been trying to POST on the create action of the OfficesController but I am getting this :

Started POST "/api/v1/association/account_assos/1/offices" for ::1 at 2016-04-26 13:54:00 +0200  Processing by Api::V1::Association::OfficesController#create as JSON    Parameters: {"office"=>{"name"=>"Samu Paris", "contact_mail"=>"samuparis@gmail.com", "contact_phone"=>"+33666027414", "address"=>"148 BD BINEAU", "city"=>"PARIS", "postcode"=>"92200", "photos_attributes"=>[{"image_url"=>""}]}, "account_asso_id"=>"1"}    User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["email", "mariashi@gmail.com"]]  Completed 500 Internal Server Error in 50ms (ActiveRecord: 1.0ms)    **NameError - uninitialized constant Api::V1::Association::OfficesController::Association:**  

My routes look like :

namespace :api, defaults: { format: :json } do        namespace :v1 do          namespace :association do            resources :account_assos, only: [ :index, :show, :update, :create ] do              resources :offices, only: [ :index, :show, :create ]            end          end        end      end  

And the problematic controller :

class Api::V1::Association::OfficesController < Api::V1::BaseController    before_action :set_office, only: [ :show, :update, :destroy]    before_action :set_account_asso, only: [:create, :index]        def index      # is this the best way ??      if (current_user.created_account_asso == @account_asso) || ((current_user.account_asso == @account_asso) && (current_user.status == "manager"))        @offices = policy_scope(office).where(account_asso: @account_asso)        render :index      else        render json: {message: "Unauthorized"}      end    end      def show      authorize @office    end      def update      authorize @office      if @Office.update(office_params)        render :show      else        render_error      end    end      # input account    def create      @office = @account_asso.offices.build(office_params)      authorize @office      if @office.save        render :show      else        render_error      end    end      def destroy      authorize @office      if @office.destroy        render json: {success: "Office successfully destroyed"}      else        render json: {error: "There was an error please try again"}      end    end      private      def set_account_asso      @account_asso = Association::AccountAsso.find(params[:account_asso_id])    end      def set_office      @office = Office.find(params[:id])    end      def Office_params      params.require(:office).permit( :name,                                      :address,                                      :contact_mail,                                      :contact_phone,                                      :address,                                      :city,                                      :postcode,                                      photos_attributes: [ :image_url ]                                    )    end      def render_error      render json: { errors: @office.errors.full_messages }, status: :unprocessable_entity    end    end  

The offices_controller is stored in api/v1/association which seems consistent to me. Why am I then getting

  **NameError - uninitialized constant Api::V1::Association::OfficesController::Association:**   

My models relative to the "association" concept are stored in models/association. This is my AccountAsso model for example (models/association/account_asso.rb) :

class Association::AccountAsso < ActiveRecord::Base      # associations    has_many :users, dependent: :destroy    has_many :offices, dependent: :destroy    belongs_to :admin, class_name: "User", foreign_key: "admin_user_id"        # validations      validates :name, presence: true, length: {minimum: 2}    validates_format_of :contact_mail,:with => Devise::email_regexp    validates :contact_tel, format: {        with:     /\A(\+33)[1-9]([-. ]?[0-9]{2}){4}\z/,        message:  'Le format de votre numéro doit être du type +33602385414'      }    validates :iban, presence: true, format: {        with:     /\A[a-zA-Z]{2}\d{2}\s*(\w{4}\s*){2,7}\w{1,4}\s*\z/,        message:  'Le format de votre IBAN doit être du type FR70 3000 2005 5000 0015 7845 Z02'      }, allow_blank: true      validates :bic, presence: true, format: {        with:     /([a-zA-Z]{4}[a-zA-Z]{2}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?)/,        message:  'Le format de votre BIC doit être du type AXABFRPP  '      }, allow_blank: true      validates :admin, presence: true, uniqueness: true        # validates :legal_status, presence: true,    end  

I get a "Pending Error" whenever I click on Pay using Payola-Payment Gem (A gem made for Stripe) in my Rails 4.2.1 application

Posted: 26 Apr 2016 05:24 AM PDT

Using Payola-Payments Gem to handle Stripe Payments, it's necessary to set Background Worker for your transaction. After setting up Background Worker using ActiveJob, I will get error when I click pay.

Here is it:

Note: Am using Windows Environment (Windows 8) and I believe there is something am doing wrong here. Error Alert Renders on my View:

This seems to be taking too long. Please contact support and give them transaction ID: ook4dp

Here is the generated code from Console

Started POST "/payola/buy/job/excelwithcode-7d492bf330ab66b0eaa61ce2ce277e14" for 127.0.0.1 at 2016-04-25 20:50:26 +0100  Processing by Payola::TransactionsController#create as */*    Parameters: {"stripeToken"=>"tok_184FksCc1zXXaitaOrD5ELaH", "stripeEmail"=>"neededforpayments@mybusinesstest.com", "authenticity_token"=>"Uod7Ue4XHNcCvayA6G1shiiI43QKoBOrbImnwt0TGFHVlp11WdHaNTcPl/0UyYefcT6foowc30bFdtK0cJuXog==", "product_class"=>"job", "permalink"=>"excelwithcode-7d492bf330ab66b0eaa61ce2ce277e14"}    Payola::Affiliate Load (1.0ms)  SELECT  "payola_affiliates".* FROM "payola_affiliates" WHERE (lower(code) = lower(NULL))  ORDER BY "payola_affiliates"."id" ASC LIMIT 1    Job Load (1.0ms)  SELECT  "jobs".* FROM "jobs" WHERE "jobs"."permalink" = ? LIMIT 1  [["permalink", "excelwithcode-7d492bf330ab66b0eaa61ce2ce277e14"]]    Payola::Coupon Load (1.0ms)  SELECT  "payola_coupons".* FROM "payola_coupons" WHERE (lower(code) = lower(NULL))  ORDER BY "payola_coupons"."id" ASC LIMIT 1     (1.0ms)  begin transaction    Payola::Sale Exists (0.0ms)  SELECT  1 AS one FROM "payola_sales" WHERE "payola_sales"."guid" IS NULL LIMIT 1    CACHE (0.0ms)  SELECT  1 AS one FROM "payola_sales" WHERE "payola_sales"."guid" IS NULL LIMIT 1    Payola::Sale Exists (1.0ms)  SELECT  1 AS one FROM "payola_sales" WHERE "payola_sales"."guid" = 'ook4dp' LIMIT 1    SQL (1.0ms)  INSERT INTO "payola_sales" ("product_id", "product_type", "email", "stripe_token", "currency", "amount", "state", "guid", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  [["product_id", 1], ["product_type", "Job"], ["email", "neededforpayments@mybusinesstest.com"], ["stripe_token", "tok_184FksCc1zXXaitaOrD5ELaH"], ["currency", "usd"], ["amount", 20000], ["state", "pending"], ["guid", "ook4dp"], ["created_at", "2016-04-25 19:50:26.639939"], ["updated_at", "2016-04-25 19:50:26.639939"]]    SQL (0.0ms)  INSERT INTO "versions" ("event", "created_at", "item_id", "item_type") VALUES (?, ?, ?, ?)  [["event", "create"], ["created_at", "2016-04-25 19:50:26.639939"], ["item_id", 2], ["item_type", "Payola::Sale"]]     (150.3ms)  commit transaction  [ActiveJob] Enqueued Payola::Worker::ActiveJob (Job ID: 72e9235d-e2f2-42d6-8ae4-0a74dd8bce5d) to DelayedJob(default) with arguments: "Payola::ProcessSale", "ook4dp"  [ActiveJob]    (0.0ms)  begin transaction  [ActiveJob]   SQL (1.0ms)  INSERT INTO "delayed_jobs" ("queue", "handler", "run_at", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["queue", "default"], ["handler", "--- !ruby/object:ActiveJob::QueueAdapters::DelayedJobAdapter::JobWrapper\njob_data:\n  job_class: Payola::Worker::ActiveJob\n  job_id: 72e9235d-e2f2-42d6-8ae4-0a74dd8bce5d\n  queue_name: default\n  arguments:\n  - Payola::ProcessSale\n  - ook4dp\n"], ["run_at", "2016-04-25 19:50:26.812282"], ["created_at", "2016-04-25 19:50:26.812282"], ["updated_at", "2016-04-25 19:50:26.812282"]]  [ActiveJob]    (87.0ms)  commit transaction  Completed 200 OK in 284ms (Views: 1.0ms | ActiveRecord: 244.3ms)      Started GET "/payola/status/ook4dp" for 127.0.0.1 at 2016-04-25 20:50:26 +0100  Processing by Payola::TransactionsController#status as */*    Parameters: {"guid"=>"ook4dp"}    Payola::Affiliate Load (1.0ms)  SELECT  "payola_affiliates".* FROM "payola_affiliates" WHERE (lower(code) = lower(NULL))  ORDER BY "payola_affiliates"."id" ASC LIMIT 1    Payola::Sale Load (1.0ms)  SELECT  "payola_sales".* FROM "payola_sales" WHERE "payola_sales"."guid" = ? LIMIT 1  [["guid", "ook4dp"]]  Completed 200 OK in 8ms (Views: 1.0ms | ActiveRecord: 2.0ms)      Started GET "/payola/status/ook4dp" for 127.0.0.1 at 2016-04-25 20:50:28 +0100  Processing by Payola::TransactionsController#status as */*    Parameters: {"guid"=>"ook4dp"}    Payola::Affiliate Load (1.0ms)  SELECT  "payola_affiliates".* FROM "payola_affiliates" WHERE (lower(code) = lower(NULL))  ORDER BY "payola_affiliates"."id" ASC LIMIT 1    Payola::Sale Load (1.0ms)  SELECT  "payola_sales".* FROM "payola_sales" WHERE "payola_sales"."guid" = ? LIMIT 1  [["guid", "ook4dp"]]  Completed 200 OK in 8ms (Views: 0.0ms | ActiveRecord: 2.0ms)  

Under Network Tab from my Browser I get the following

{guid: "ook4dp", status: "pending", error: null}  error: null  guid: "ook4dp"  status: "pending"  

config/application.rb

require File.expand_path('../boot', __FILE__)    require 'rails/all'  require 'active_job'  require 'active_record'  require 'action_controller'  require 'action_view'    # Require the gems listed in Gemfile, including any gems  # you've limited to :test, :development, or :production.  Bundler.require(*Rails.groups)    module App    class Application < Rails::Application      config.i18n.enforce_available_locales = true        config.action_controller.action_on_unpermitted_parameters = :raise      # Settings in config/environments/* take precedence over those specified here.      # Application configuration should go into files in config/initializers      # -- all .rb files in that directory are automatically loaded.        # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.      # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.      # config.time_zone = 'Central Time (US & Canada)'        # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.      # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]      # config.i18n.default_locale = :de        config.active_record.raise_in_transactional_callbacks = true        config.active_job.queue_adapter = :delayed_job      end  end  

model/job.rb

class Job < ActiveRecord::Base    include Payola::Sellable      validates :title,              :category,              :location,              :description,              :company_name,              :website,              :email,              :to_apply,              presence: true    validates :title, length: { maximum: 75 }    validates :description, length: { minimum: 300 }    validates :to_apply, length: { maximum: 500 }      validates_formatting_of :email, using: :email    validates_formatting_of :website, using: :url      before_validation :provide_name, :provide_permalink      def self.paid_ad      where.not('stripeEmail' => nil).where.not('payola_sale_guid' => nil).where('created_at > ?', 30.days.ago)    end      def paid?      (!(self.stripeEmail == nil) && !(self.payola_sale_guid == nil))    end      def self.search(params)      jobs = Job.where('name like ? or description like?', "%#{params[:search]}%', '%#{params[:search]}%" ) if params [:search]      jobs    end        private      def provide_name      self.name = 'excelwithcode' if self.name == nil    end      def provide_permalink      self.permalink = "#{ self.name } #{ SecureRandom.hex }".parameterize if self.permalink == nil    end  end  

Looking at my development log, I understand the transaction keeps repeating itself because of Background Worker using ActiveJob which I set, but the main problem is that the transaction never gets successful and my Error alert responds on my Stripe Custom Payment Form as described above. In other words, once you click PAY, it freezes.

I still don't know why this happened and I need your help. Thanks for helping in advance

Heroku H10 error "App Crashed"

Posted: 26 Apr 2016 06:03 AM PDT

I'm trying to deploy my Ruby on Rails webbapp to Heroku. Locally it works just fine but when I try to run it through Heroku is gives me a H10 error HTTP status 503. I guess it's because of the bash: bundle: command not found. But even running heroku run bundle exec rails server -p $PORT doesn't work.

  2016-04-26T11:35:09.570021+00:00 heroku[slug-compiler]: Slug compilation started      2016-04-26T11:35:09.570027+00:00 heroku[slug-compiler]: Slug compilation failed: failed to compile Ruby app      2016-04-26T11:36:34.435961+00:00 heroku[slug-compiler]: Slug compilation started      2016-04-26T11:36:34.435967+00:00 heroku[slug-compiler]: Slug compilation failed: failed to compile Ruby app      2016-04-26T11:37:06.665673+00:00 heroku[slug-compiler]: Slug compilation started      2016-04-26T11:37:06.665682+00:00 heroku[slug-compiler]: Slug compilation failed: failed to compile Ruby app      2016-04-26T11:37:20.446113+00:00 heroku[slug-compiler]: Slug compilation started      2016-04-26T11:37:20.446119+00:00 heroku[slug-compiler]: Slug compilation failed: failed to compile Ruby app      2016-04-26T11:37:26.534228+00:00 heroku[web.1]: State changed from crashed to starting      2016-04-26T11:37:32.239987+00:00 heroku[web.1]: Starting process with command `bundle exec rails server -p 48566`      2016-04-26T11:37:34.485283+00:00 app[web.1]: bash: bundle: command not found      2016-04-26T11:37:35.145372+00:00 heroku[web.1]: Process exited with status 127      2016-04-26T11:37:35.160181+00:00 heroku[web.1]: State changed from crashed to starting      2016-04-26T11:37:35.157438+00:00 heroku[web.1]: State changed from starting to crashed      2016-04-26T11:37:40.225006+00:00 heroku[web.1]: Starting process with command `bundle exec rails server -p 57613`      2016-04-26T11:37:41.536602+00:00 app[web.1]: bash: bundle: command not found      2016-04-26T11:37:42.254167+00:00 heroku[web.1]: Process exited with status 127      2016-04-26T11:37:42.273228+00:00 heroku[web.1]: State changed from starting to crashed      2016-04-26T11:37:43.433890+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=justarandomname-sandbox.herokuapp.com request_id=4570bf17-d1d5-46f8-a2fa-9b3903e5f7b8 fwd="78.128.33.2" dyno= connect= service= status=503 bytes=      2016-04-26T11:37:43.875014+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=justarandomname-sandbox.herokuapp.com request_id=bef38221-b815-42f0-bff9-a5af6ec9faef fwd="78.128.33.2" dyno= connect= service= status=503 bytes=      2016-04-26T11:37:43.928876+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=justarandomname-sandbox.herokuapp.com request_id=af6d1b23-6fca-4936-831a-8be720931110 fwd="78.128.33.2" dyno= connect= service= status=503 bytes=      2016-04-26T11:38:18.973552+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=justarandomname-sandbox.herokuapp.com request_id=bdcbfa80-b930-458c-9838-22d143092149 fwd="78.128.33.2" dyno= connect= service= status=503 bytes=      2016-04-26T11:38:30.012185+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=justarandomname-sandbox.herokuapp.com request_id=7e6af745-e613-448c-be0e-be6c14c4499e fwd="78.128.33.2" dyno= connect= service= status=503 bytes=      2016-04-26T11:38:31.797207+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=justarandomname-sandbox.herokuapp.com request_id=11006d32-abf4-481e-896e-3da3a9778902 fwd="78.128.33.2" dyno= connect= service= status=503 bytes=      2016-04-26T11:38:33.450964+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=justarandomname-sandbox.herokuapp.com request_id=731c163d-73dc-49d8-9334-96621b9afa99 fwd="78.128.33.2" dyno= connect= service= status=503 bytes=      2016-04-26T11:38:35.451317+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=justarandomname-sandbox.herokuapp.com request_id=1bf2c73c-cd8e-4b4a-a9c2-967934186c3f fwd="78.128.33.2" dyno= connect= service= status=503 bytes=  

Additional info

Procfile:

web: bundle exec rails server -p $PORT  console: bundle exec rails console  

Heroku config vars:

PATH        => bin:vendor/bundle/ruby/2.0.0/bin:qr/qrencode-3.2.0:bin:/.bin:/usr/local/bin:/usr/bin:/bin  GEM_PATH    => vendor/bundle/ruby/2.0.0  RACK_ENV    => production  RAILS_ENV   => production  

Heroku buildpacks:

https://github.com/incaztech/heroku-buildpack-qrencode.git

Rspec (for Michael Hartl example) for the definition of relationship following users

Posted: 26 Apr 2016 05:29 AM PDT

I'm trying to make a spec test for the MHartl's example. As it follows bellow my difficult is for #Follows a user.

class User < ActiveRecord::Base      # Associations    has_many :active_relationships, class_name:  "Relationship",                                    foreign_key: "follower_id",                                    dependent:   :destroy    has_many :following, through: :active_relationships, source: :followed    has_many :followers, through: :passive_relationships, source: :follower        # Follows a user.    def follow(other_user)      active_relationships.create(followed_id: other_user.id)    end  

For my spec:

require 'rails_helper'    RSpec.describe User, :type => :model do    let(:user) { build(:user) }      describe 'Validations' do      it 'has a valid factory' do        expect(user).to be_valid      end        it { should validate_presence_of(:email) }      it { should validate_presence_of(:password) }      it { should validate_confirmation_of(:password) }    end        let(:user) { create(:user) }    let(:other_user) { create(:user) }      describe 'following utility methods' do      it "user starts to follow other user" do        user.follow(other_user)        user.following?(other_user).should be_valid      end    end  end  

My failures :

  1) User following utility methods user starts to follow other user       Failure/Error: user.following?(other_user).should be_valid         NoMethodError:         undefined method `should' for true:TrueClass  

If you need more info about this post, please fell free to ask! and please tell me were can I learn more about this specs tests. thanks for your help :)

Can i add <textarea> inside Tinymce editor?

Posted: 26 Apr 2016 04:58 AM PDT

I integrated Tinymce in Rails 4 application. Now, i added content in Tinymce from admin and display it front side and works fine.

But as per requirements, I have to add <textarea> <input> tags into Tinymce editor and display it front side in HTML format.

I tried lots but not get any idea. Any one have trick or idea in it.

Thanks

Rails Wicked Gem - Flash Messages

Posted: 26 Apr 2016 04:50 AM PDT

I have a Campaign model and I am using Wicked Gem for step by step campaign creation.

I have total 3 steps in the wizard...

steps :details, :audiance, :creatives  

Here is my Wizard controller

class Brands::CampaignWizardsController < Brands::ApplicationController    include Wicked::Wizard    steps :details, :audiance, :creatives      def show      @campaign = current_company.campaigns.friendly.find(params[:campaign_id])      render_wizard    end      def update      case step        when :details          @campaign.attributes = campaign_details_params            @campaign[:dos].delete_if(&:blank?)          @campaign[:donts].delete_if(&:blank?)            @campaign_ideas = CampaignIdea.where(objective_id: @campaign.objective_id)          when :audiance          @campaign.attributes = campaign_audiance_params            @campaign[:influencer_interests].delete_if(&:blank?)          when :creatives          @campaign.attributes = campaign_creatives_params        end      render_wizard @campaign    end  end  

I would like to add flash messages (success/error) in each step of the wizard.

Is there any way to pass my messages as an option{} to render_wizard ?

How to list record as json for outer join active record

Posted: 26 Apr 2016 05:06 AM PDT

i created active record through outer join and rendering json. when i render this i'm not getting outer joined table datas. how to fetch it

@recent_details = Property    .includes(:space_amenities,:event_suitabilities,:purpose_suitabilities,:venue_categories)    .where(id: params[:id])  render json: @recent_details  

this is how i rendered index.jbuiler.json form

json.recent_details @recent_details  

here i got all details from properties table except the outer join tables. how to get the outer joined table results here

Generated rspec test fails when testing POST with invalid params

Posted: 26 Apr 2016 04:57 AM PDT

I'm new with rails and trying to complete the generated rspec tests for my controller garden with invalid parameters.

I want square_feet to always be supplied, but the error I'm getting appears to be complaining that there is no default value for the gardens table. This confuses me; I don't want to set a default value for square_feet and I don't understand why the application isn't erroring out and redirecting the user when it sees a null value?

The only part of the generated test that I edited is the let() statements. What do I have to do to get these tests to pass?

Rspec test:

RSpec.describe GardensController, type: :controller do      let(:valid_attributes) { FactoryGirl.attributes_for(:garden) }    let(:invalid_attributes) { {:name => nil, :square_feet => nil, :zone => nil} }    let(:valid_session) { {} }      describe "POST #create" do      context "with invalid params" do          it "assigns a newly created but unsaved garden as @garden" do          post :create, {:garden => invalid_attributes}, valid_session          expect(assigns(:garden)).to be_a_new(Garden)        end          it "re-renders the 'new' template" do          post :create, {:garden => invalid_attributes}, valid_session          expect(response).to render_template("new")        end              end    end    end  

Factory:

FactoryGirl.define do    factory :garden do      name "MyString"      square_feet 1      zone 1      garden_type "MyString"      user nil    end  end  

DB Schema:

mysql> describe gardens;  +-------------+--------------+------+-----+---------+----------------+  | Field       | Type         | Null | Key | Default | Extra          |  +-------------+--------------+------+-----+---------+----------------+  | id          | int(11)      | NO   | PRI | NULL    | auto_increment |  | name        | varchar(255) | NO   |     | NULL    |                |  | square_feet | int(11)      | NO   |     | NULL    |                |  | zone        | int(11)      | NO   |     | NULL    |                |  | garden_type | varchar(255) | YES  |     | NULL    |                |  | user_id     | int(11)      | YES  | MUL | NULL    |                |  | created_at  | datetime     | NO   |     | NULL    |                |  | updated_at  | datetime     | NO   |     | NULL    |                |  +-------------+--------------+------+-----+---------+----------------+  8 rows in set (0.00 sec)  

Rspec errors:

1) GardensController POST #create with invalid params assigns a newly created but unsaved garden as @garden       Failure/Error: if @garden.save         ActiveRecord::StatementInvalid:         Mysql2::Error: Field 'square_feet' doesn't have a default value: INSERT INTO `gardens` (`created_at`, `updated_at`) VALUES ('2016-04-26 11:25:08', '2016-04-26 11:25:08')       # ./app/controllers/gardens_controller.rb:30:in `block in create'       # ./app/controllers/gardens_controller.rb:29:in `create'       # ./spec/controllers/gardens_controller_spec.rb:91:in `block (4 levels) in <top (required)>'       # ------------------       # --- Caused by: ---       # Mysql2::Error:       #   Field 'square_feet' doesn't have a default value       #   ./app/controllers/gardens_controller.rb:30:in `block in create'      2) GardensController POST #create with invalid params re-renders the 'new' template       Failure/Error: if @garden.save         ActiveRecord::StatementInvalid:         Mysql2::Error: Field 'square_feet' doesn't have a default value: INSERT INTO `gardens` (`created_at`, `updated_at`) VALUES ('2016-04-26 11:25:08', '2016-04-26 11:25:08')       # ./app/controllers/gardens_controller.rb:30:in `block in create'       # ./app/controllers/gardens_controller.rb:29:in `create'       # ./spec/controllers/gardens_controller_spec.rb:96:in `block (4 levels) in <top (required)>'       # ------------------       # --- Caused by: ---       # Mysql2::Error:       #   Field 'square_feet' doesn't have a default value       #   ./app/controllers/gardens_controller.rb:30:in `block in create'      3) GardensController PUT #update with invalid params assigns the garden as @garden       Failure/Error: if @garden.update(garden_params)         ActiveRecord::StatementInvalid:         Mysql2::Error: Column 'square_feet' cannot be null: UPDATE `gardens` SET `square_feet` = NULL, `zone` = NULL, `updated_at` = '2016-04-26 11:25:08' WHERE `gardens`.`id` = 101       # ./app/controllers/gardens_controller.rb:44:in `block in update'       # ./app/controllers/gardens_controller.rb:43:in `update'       # ./spec/controllers/gardens_controller_spec.rb:131:in `block (4 levels) in <top (required)>'       # ------------------       # --- Caused by: ---       # Mysql2::Error:       #   Column 'square_feet' cannot be null       #   ./app/controllers/gardens_controller.rb:44:in `block in update'      4) GardensController PUT #update with invalid params re-renders the 'edit' template       Failure/Error: if @garden.update(garden_params)         ActiveRecord::StatementInvalid:         Mysql2::Error: Column 'square_feet' cannot be null: UPDATE `gardens` SET `square_feet` = NULL, `zone` = NULL, `updated_at` = '2016-04-26 11:25:08' WHERE `gardens`.`id` = 102       # ./app/controllers/gardens_controller.rb:44:in `block in update'       # ./app/controllers/gardens_controller.rb:43:in `update'       # ./spec/controllers/gardens_controller_spec.rb:137:in `block (4 levels) in <top (required)>'       # ------------------       # --- Caused by: ---       # Mysql2::Error:       #   Column 'square_feet' cannot be null       #   ./app/controllers/gardens_controller.rb:44:in `block in update'    Finished in 0.17718 seconds (files took 3 seconds to load)  16 examples, 4 failures, 1 pending    Failed examples:    rspec ./spec/controllers/gardens_controller_spec.rb:90 # GardensController POST #create with invalid params assigns a newly created but unsaved garden as @garden  rspec ./spec/controllers/gardens_controller_spec.rb:95 # GardensController POST #create with invalid params re-renders the 'new' template  rspec ./spec/controllers/gardens_controller_spec.rb:129 # GardensController PUT #update with invalid params assigns the garden as @garden  rspec ./spec/controllers/gardens_controller_spec.rb:135 # GardensController PUT #update with invalid params re-renders the 'edit' template  

Add angular-chart.js to Rails application.js file

Posted: 26 Apr 2016 06:44 AM PDT

I'm trying to setup angular-chart.js in an Angular on Rails application, per github instructions. But the documentation is not specifically for Rails so I'm running into errors.

Installation instruction: http://jtblin.github.io/angular-chart.js/

For reference,

  1. installed via bower, bower install angular-chart.js --save
  2. added as dependency, angular.module('myModule', ['chart.js']);.

Documentation then recommends then adding <script src="bower_components/angular-chart.js/dist/angular-chart.js"></script>, but this file is not found if I add this line (think because using Rails).

Since the application is Angular ontop of Rails, I assume it needs to be added to Rails application.js file. As otherwise there is an angular no module error.

But I'm not sure exactly what needs to be added to application.js. I've tried:

  • chart.js
  • angular-chart.js
  • angular-chart

(prefaced by //= require)

But everything results in a Rails error,

Sprockets::FileNotFound in Boards#index  couldn't find file 'chart.js' with type 'application/javascript'  

Is there a way to find out exactly what needs to be added to application.js? Or some other way to solve this?

(Apologies if this is difficult to follow.)

Rspec mailer test with devise link

Posted: 26 Apr 2016 04:16 AM PDT

I have custom UserMailer, which have devise link- edit_password_path. Now I need write tests:

require "rails_helper"    RSpec.describe UserMailer, type: :mailer do      describe "#invitation" do      let!(:user) { create(:user) }      let!(:correspondence) { create(:correspondence) }      let!(:mail) { UserMailer.invitation(user, user.password) }        it "renders the headers" do        expect(mail.subject).to eq(correspondence.invitation_subject)        expect(mail.to).to eq(user.email)      end     end  end  

error:

NoMethodError: undefined method `edit_password_url' for #<UserMailer:0x005604b3309248>  

How Can I include urls to my mailer tests in rspec?

Ruby on Rails: RatyRates Gem displaying numbers instead of stars

Posted: 26 Apr 2016 04:12 AM PDT

Model: homework.rb

class Homework < ActiveRecord::Base     validates :subject, presence:true        belongs_to :user      belongs_to :classmodule      has_many :hw_comments      has_many :hw_instances        ratyrate_rateable 'difficulty', 'interest'  

homeworks/show.html.erb

    <div class="row">    <div class="small-2 large-2 columns">        <%= imdb_style_rating_for @homework, current_user%>    </div>    <br>      <div class="small-2 large-4 columns">        <% if current_user %>        Difficulty: <%= rating_for @homework, "difficulty", stars: 10 %>        <br>          Interest: <%= rating_for @homework, "interest", stars: 10 %>        <% end %>  

I am using the ratyrate gem to add rating functionality to a user so they can rate their homework. The gem uses stars to show a rating. I would like to change these to numbers and I am looking for a way to do this if possible. Thanks.

Creating engine with ruby on rails

Posted: 26 Apr 2016 05:21 AM PDT

I am creating an engine, and I have some problems.

I`m reading this manual

and my project has the following information:

  • path to my main application: /var/www/crs
  • path to my engine, myapp: /var/www/crs/myapp

These are the steps I tried:

  1. I ran this code: rails plugin new myapp --mountable

  2. I created the resource in /var/www/crs/myapp/test/dummy/

  3. I added to /var/www/crs/config/routes.rb the line mount Myapp::Engine => "/myapp"

  4. I ran in the console (/var/www/crs/myapp/test/dummy/) this code: rails s

So far so good. However, when I added to the gem file in main app (/var/www/crs/Gemfile ) this line:

gem 'myapp', path: "myapp"  

and executed the command

bundle  

I got the following erros:

The gemspec at /var/www/crs/myapp/myapp.gemspec is not valid. The validation error was '"FIXME" or "TODO" is not a description'  Could not find gem 'myapp' in source at `myapp`.  Source does not contain any versions of 'myapp'  

I don't understand where this error is comming from, nor do I know where the file that is having it is. How can I find the troublematic file and how can I fix this?

Rails 4 - .m3u8 video is not loading

Posted: 26 Apr 2016 03:54 AM PDT

In rails 4.2.2, I am trying to load one .m3u8 video but it is not loading and playing.

<video autobuffer="autobuffer" autoplay="autoplay" width="480" height="320" controls="controls" src="https://d3hvssado3w9w.cloudfront.net/sample_test/rswrs7k7wa6n9/69c3e699-9bba-4c42-91cd-90gd61823258/index.m3u8"></video>  

How can I fix this issue? Please help me.

Searchkick results are not relevant

Posted: 26 Apr 2016 06:06 AM PDT

I have a problem with a relevant search. Results of following request are very strange:

Candidate.search('martin', fields: [:first_name, :last_name],                              match: :word_start, misspellings: false).map(&:name)      ["Kautzer Martina",   "Funk Martin",   "Jaskolski Martin",   "Gutmann Martine",   "Wiegand Martina",   "Schueller Martin",   "Dooley Martin",   "Stiedemann Martine",   "Bartell Martina",   "Gerlach Martine",   "Green Martina",   "Lang Martine",   "Legros Martine",   "Ernser Martina",   "Boehm Martina",   "Green Martine",   "Nolan Martin",   "Schmidt Martin",   "Hoppe Martin",   "Macejkovic Martine",   "Emard Martine"]  

Why Martina is going earlier than Martin?

Searckick config:

searchkick language: %w(German English), word_start: [:first_name, :last_name]  

What's this "from ... to" in my mysql table schema?

Posted: 26 Apr 2016 04:03 AM PDT

I wrote a simple rails migration to set the default value on the name column of my gardens table:

class ChangeColumnDefaultToGarden < ActiveRecord::Migration    def up       change_column_null :gardens, :name, false      change_column_default :gardens, :name, from: nil, to: ""      change_column_null :gardens, :square_feet, false      change_column_null :gardens, :zone, false    end      def down      change_column_null :gardens, :name, true      change_column_default :gardens, :name, from: "", to: nil      change_column_null :gardens, :square_feet, true      change_column_null :gardens, :zone, true    end    end  

When I run the migration and describe the table I see this:

mysql> describe gardens;  +-------------+--------------+------+-----+----------------------+----------------+  | Field       | Type         | Null | Key | Default              | Extra          |  +-------------+--------------+------+-----+----------------------+----------------+  | id          | int(11)      | NO   | PRI | NULL                 | auto_increment |  | name        | varchar(255) | YES  |     | ---  :from: ''  :to:   |                |  | square_feet | int(11)      | YES  |     | NULL                 |                |  | zone        | int(11)      | YES  |     | NULL                 |                |  | garden_type | varchar(255) | YES  |     | NULL                 |                |  | user_id     | int(11)      | YES  | MUL | NULL                 |                |  | created_at  | datetime     | NO   |     | NULL                 |                |  | updated_at  | datetime     | NO   |     | NULL                 |                |  +-------------+--------------+------+-----+----------------------+----------------+  8 rows in set (0.17 sec)  

What is that :from: "" and :to:? I'm not familiar with that mysql syntax.

No comments:

Post a Comment