mardi 4 août 2015

Failing to pass arbitrary form parameters to Rails controller

I have a form with several fields that aren't in my model but I'm not able to access them inside my controller.

My new form is fairly simple and was generated with some rails scaffolding. It's inside my controller's create method that I'm not able to access these params.

I've added the params with attr_accessor to my controller, which looks something like:

class LittleClassSessionsController < ApplicationController
  before_action :set_event_session, only: [:show, :edit, :update, :destroy]
  attr_accessor :schedule_type

My view has a form field that looks like this. I can see the parameter's value being submitted in the console.

<select name="schedule_type" id="schedule_type">
  <option value="1">Recurring— Create a series of class sessions in advance</option>
  <option value="2">Not recurring— Create just one class session in advance</option>
</select>

I've added :schedule_type to my whitelisted params. When trying to puts the params to my console, it's not in there.

What am I missing?



via Chebli Mohamed

ActionController::RoutingError (No route matches [GET] "/scan"):

Getting an error for a simple index route in rails:

Here are my routes:

Prefix Verb URI Pattern           Controller#Action
scan_index GET  /scan/index(.:format) scan#index
      root GET  /                     scan#index
      scan GET  /scan(.:format)       scan#index

Yet, typing in the following url:

http://ift.tt/1Ulkpus

Produces the following in error_log:

I, [2015-08-04T15:38:42.902191 #24943]  INFO -- : Started GET "/scan" at 2015-08-04 15:38:42 +0000
F, [2015-08-04T15:38:42.902936 #24943] FATAL -- : 
ActionController::RoutingError (No route matches [GET] "/scan"):



via Chebli Mohamed

Rails - Controller that does not check for CSRF token

In my rails application, one of the controllers displays public statistics that I want websites hosted on different domains to pull data from. (http://ift.tt/1ML3M9n)

My controller code is given below:

class StatsController < ApplicationController 
require 'ostruct'
skip_before_action :verify_authenticity_token
respond_to :html, :xml, :json, :csv

def index
    @stats = OpenStruct.new
    @stats.users = User.all.count
    @stats.organizations = Organization.all.count
    @stats.donors = Person.all.count
    respond_to do |format|
        format.json {render json: @stats}
    end
end
end

I thought the line skip_before_action :verify_authenticity_token would be enough, but when I try to make requests to this page from the console, I get the following error:

XMLHttpRequest cannot load http://ift.tt/1ML3M9n. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

How can I fix this?



via Chebli Mohamed

How do I specify the join table on a has_many through association?

I have a users table (admin_users) a join table (UserCompanies) and a companies table (Companies), each has an active record model (AdminUser, TableModule::UserCompany, TableModule::Company). I want to do something like the following:

AdminUser.first.companies

But, my attempts so far are not working, I'm assuming because I need to specify the table names, model names, or key names, but I don't know how that works with a has_many through relationship. Here is my best attempt at defining it so far:

class AdminUser < ActiveRecord::Base
    has_many :companies, through: :user_company, source: "TableModule::UserCompany"
end

How do I properly specify this relationship?



via Chebli Mohamed

Unable to send mail with attachment using Mandrill-api gem (Rails 4.1)

Emails without attachment are delivered fine, but when there is an attachment I get the following error in production:

ArgumentError: An SMTP To address is required to send a message. Set the message smtp_envelope_to, to, cc, or bcc address.

  • Letter opener in dev model shows the email rendering perfectly
  • This error only shows up in production

the call to mailer is:

# template variables
merge_vars = {"AMOUNT" => "100"}

invoice = Invoice.new(customer)

attachments[invoice.name] = {
  data: invoice.invoice_data,
  mime_type: 'application/pdf'
}

mail(to: user.email, cc: cc_emails.compact.uniq, subject: mail_subject, content_type: content_type) do |format|
  # Template renders fine
  format.html{mandrill_template('invoice_template', merge_vars)}
end

InvoiceMailer < ActionMailer::Base has defaults for "from" and "reply_to"

Mandril gem version 1.0.53 and Rails 4.1.10.



via Chebli Mohamed

How can I call a method within active_scaffold?

I can't seem to find any questions similar to this that have been asked. Maybe this means I am way off and this is a dumb question.

I am trying to add a feature to a preexisting app. This feature allows the user to copy a report over to the next period (a fiscal year).

Here is the abridged active_scaffold code:

active_scaffold :report do |config|
  config.list.columns = [:user, :period, :division, :released, :reportable, :comp_plan]
  config.create.columns = [:user, :period, :division, :released, :reportable, :comp_plan]
  config.update.columns = [:user, :period, :division, :released, :reportable, :comp_plan]

  config.actions.exclude :show

  config.columns[:user].form_ui = :select
  config.columns[:period].form_ui = :select

  config.columns[:user].clear_link
  config.columns[:period].clear_link

  config.columns[:user].search_sql = ["users.first_name", "users.last_name"]
  config.search.columns << :user

  config.nested.add_link :access_rights, :label => 'Access'
end

Now I want to add a link to each row which calls a function which copies that report.

Any ideas are greatly appreciated.

Edit: Most of the code probably isn't relevant to the question but I figure it would be helpful to see anyways.



via Chebli Mohamed

Paperclip S3 Bucket and Rails Images will upload but will not display

I am using paperclip gem along with an AWS s3 bucket to upload images to my app. I have it all working properly and the images will upload to the actual bucket and the web pages will load. The only problem is the images themselves will not display and it will only display their names like enter image description here

to display the image I am using the code

<%= image_tag @post.image.url(:medium), class: "edit_recipe_image" %>

has any one experiences this before or possibly know a solution to fix this?

Thanks in advance!



via Chebli Mohamed

Android post json to API in background

i have two applications, i have the android app and the Ruby on Rails API. In android i have a SQLite database and almost all the time i need sync the android database with the API database, but this synchronization can take a "long time", something like 10 seconds if is the first sync, so user need to keep waiting and looking to load screen until the process done.

So, i want send a post to the Ruby on Rails application, but without "stop" the application in the load screen, i want to do this sync in background, so the user wont realise that the app is syncing with the API.

Now, i'm trying to working with threads, but it still fails.

Thanks.



via Chebli Mohamed

How to use devise_token_auth with Devise, Angular and Mongoid

I'm trying to use Mongoid, devise, devise_token_auth and ng-token-auth for an token based authorisation for an API written in Rails with Mongoid and Angular as the client.

The problem is when I follow the steps to install devise_token_auth I get an error when I restart my Rails app: undefined methodtable_exists?' for User:Class`

I'm assuming that because I'm using Mongoid the User class don't have the table_exists? method.

How can I get around this? Or, more importantly how can I get this to work?

EDIT: Here's my User class

class User

  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Enum

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  ## Database authenticatable
  field :email,              type: String, default: ""
  field :encrypted_password, type: String, default: ""

  ## Recoverable
  field :reset_password_token,   type: String
  field :reset_password_sent_at, type: Time

  ## Rememberable
  field :remember_created_at, type: Time

  ## Trackable
  field :sign_in_count,      type: Integer, default: 0
  field :current_sign_in_at, type: Time
  field :last_sign_in_at,    type: Time
  field :current_sign_in_ip, type: String
  field :last_sign_in_ip,    type: String

  ## Confirmable
  field :confirmation_token,   type: String
  field :confirmed_at,         type: Time
  field :confirmation_sent_at, type: Time
  field :unconfirmed_email,    type: String # Only if using reconfirmable

  include DeviseTokenAuth::Concerns::User

  attr_accessor :reset_token

  enum :role, [:admin, :author]

  after_initialize :set_default_role, :if => :new_record?
  before_create :set_auth_token

  field :first_name,                                        type: String
  field :last_name,                                         type: String
  field :domain,                                                type: String
  field :payment_details,                               type: Hash
  field :subscriber,                                        type: Boolean
  field :stripe_details,                                type: Hash
  field :theme,                                                 type: String

  # Validation
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(?:\.[a-z\d\-]+)*\.[a-z]+\z/i
    before_save { self.email = email.downcase }
    before_create :create_remember_token


  # Get rid of devise-token_auth issues from activerecord
  def table_exists?
    true
  end

  def columns_hash
    # Just fake it for devise-token-auth; since this model is schema-less, this method is not really useful otherwise
    {} # An empty hash, so tokens_has_json_column_type will return false, which is probably what you want for Monogoid/BSON
  end

  def set_default_role
      self.role ||= :admin
  end

end

EDIT 2: Adding stack trace

http://ift.tt/1P4iXd5



via Chebli Mohamed

Passenger Phusion sub-uri with Apache HTTPD without virtualHost Ruby on Rails 4

Trying to deploy my application to a sub-uri. such as, [IP ADDRESS]/sub-domain instead of just [IP address]. so, the instructions at passenger assume that you have a virtualhost already established in your code (http://ift.tt/1IW0ror). Does anybody know how to get this working with the latest version of Passenger and Rails in the HTTPD config file?



via Chebli Mohamed

attr_accessible error on rails 4.1.8 upon performing rake db:migrate on heroku

I am still learning Ruby (so I am a complete noob), right now I have my app successfully running locally but when trying to opening the apps on heroku , in which I first perform the heroku run rake db:migrate I stumbled upon a problem.. it tells me :

Running `rake db:migrate` attached to terminal... up, run.2149
-- attr_accessible(:pName, :pQuantity, :pMeter, :pWeight, :pSellPrice,  :pCategory, :pPic)
-- attr_accessible(:pName, :pQuantity, :pMeter, :pWeight, :pSellPrice, :pCategory, :pPic)
rake aborted!
NoMethodError: undefined method `attr_accessible' for #<ActiveRecord::Migration:0x007f2dc2ba45b8>
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:648:in `block in method_missing'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:621:in `block in say_with_time'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:621:in `say_with_time'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:641:in `method_missing'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:406:in `method_missing'
/app/db/migrate/20150802134246_create_inventories.rb:2:in `<class:CreateInventories>'
/app/db/migrate/20150802134246_create_inventories.rb:1:in `<top (required)>'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:247:in `require'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:247:in `block in require'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:232:in `load_dependency'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:247:in `require'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:761:in `load_migration'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:757:in `migration'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:752:in `disable_ddl_transaction'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:1044:in `use_transaction?'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:954:in `rescue in block in migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:951:in `block in migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:948:in `each'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:948:in `migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:807:in `up'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:785:in `migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/railties/databases.rake:34:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:migrate

I have been trying to find out the reason, after wondering around I found out about change in rails 4.0.0 in that attr_accessible are no longer used and we should use strong parameter instead, So removing the attr_accessible from model will solve the problem...

However, I have an empty Model, there is no attr_accessible everywhere i look. (beside this is weird why my apps runs locally but not on heroku?) I can't figured out why this error appear and where to look for solutions.. I have been trying to look at active_record file but am afraid of making any changes, any idea?

also, could anyone tell me any resources that can help me read this type of log errors? I have tried to read some articles but can't find one that is easy to understand for noobs like me... ;(



via Chebli Mohamed

Dragonfly images in a polymorphic association syntax?

I have a pictures model:

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

And then I have two different models that should be able to have pictures:

class Teacher < User 
  has_many :pictures, as: :imageable  
end

class Student < User 
  has_many :pictures, as: :imageable
end

I followed instruction here to setup dragonfly and had it working when I just had one model with an image attribute but now that I want to make its own picture model that other models can have_many of then it stops working: http://ift.tt/1P4iXd3

In my rails console I can do something like:

teacher = Teacher.last
teacher.pictures 

and get returned an empty active record proxy:

#<ActiveRecord::Associations::CollectionProxy []>

but I cannot do:

teacher = Teacher.last
teacher.image
teacher.picture.image
teacher.pictures.image

When I try to display on my show view:

<%= image_tag @teacher.pictures.thumb('400x200#').url if @teacher.pictures_stored? %>

I get

undefined method `pictures_stored?'

Even if I delete the if @scientist.pictures_stored? I then get this error: undefined method thumb'

I have tried different combinations since dragonfly gives us the dragonfly_accessor :image on our pictures model. But not sure how to actually reference it. Any help is appreciated.



via Chebli Mohamed

mongoid-4 how to validate uniqueness of belongs_to in 1 to 1 association

I have a 1-to-1 association between 2 mongoid models and I keep getting duplicates, that is having more than one child record(card) with same parent_id(that is user). I have tried validating uniqueness of the belongs_to association has shown below, but it doesn't work.

 class User
   include Mongoid::Document
   field :name, type: String 
   has_one :card
 end

The second model:

 class Card
   include Mongoid::Document
   field :name, type: String 
   belongs_to :user

   validates :user, :uniqueness => {:scope => :user_has_child}

   def user_has_child
     q = Segment.where(drop_id: {'$ne' =>  nil})
     s = q.map(&:drop_id)
     errors.add(:drop_id, "this user already has a card") if s.include?(:drop_id)
   end

 end



via Chebli Mohamed

Modify Devise SAML Attributes

I'm using Rails 4 and Devise with Devise SAML Authenticatable for my Account system.

I've got the SAML working and all, but am trying to work out one thing.

I'd like to change one of the SAML attributes before saving it (since it is formatted incorrectly). Essentially, the Account's SAML request is given a role attribute which is one of the following Group_admin, Group_consumer, Group_supplier. I have a role field in my Account model enumerated as follows:

enum role: [:admin, :consumer, :supplier]

Clearly I can't directly set role because Group_admin != admin (etc.). Is there a way to modify the SAML attribute that is given before Devise saves the field?

I've tried a before_save filter to no avail.

before_save :fix_role!

private
def fix_role!
  self.role = self.role.split('_')[1]
end

Does anyone know of a way to do this? I can post any other code if necessary, I'm just not sure what else is needed. Thanks.



via Chebli Mohamed

How do I call exposed methods in C# DLL from Ruby on Linux using Mono?

I have a DLL which contains code that I would like to access from Microsoft Visual Foxpro as well as Ruby on Rails.

I set up a C# DLL and generated the corresponding .so file using Mono according to this question. mono --aot -O=all dlltest.so

As noted in that question, the function nm -Ca dlltest.so shows a form of my method, but FFI cannot see it.

Also as mentioned in that question, nm -D --defined-only dlltest.so indicates that my method is not defined. However, FFI can see and access the one that is defined as mono_aot_file_info.

It seems like the poster of that question was close to getting it to work, but I was unable to find anything about why the method is showing as not defined or how to change that.

Is there something I can do to define the methods in the .so file? Or is this not possible?

Note that the method is exposed in the DLL, and FoxPro can access it just fine.



via Chebli Mohamed

Ruby on Rails frontend and Java backend architecture?

I am building a Ruby on Rails webapp and it is great for the web front end, display, what the user sees etc. But I want request from a user that involves some heavy processing to be done inside a Java backend layer.

So my question what do you think is the best approach for joining these two layers up? I can think of two approaches:

  1. Building up the request into a JSON object in the Ruby on Rails layer and using RabbitMQ to send it as a message to the Java backend layer which sends another JSON object back in a message as a response. I tend to lean more towards this approach as there a nice RabbitMQ clients for Ruby and Java.

  2. Have a my Java layer running on a web server(such as Tomcat or maybe Netty?) that accepts HTTP requests from the Ruby on Rails layer and sends the response back through the server using HTTP?

Note any persistence will be handled by the Java layer also.

Any more ideas or and/or comments on the above two ideas would be great.

Thanks.



via Chebli Mohamed

Random order using mongoid on rails 4

I trying to get results in random order, but I can't find anything in the documentation. I want something like order random on postgresql

 .order("RANDOM()")

thanks in advance.



via Chebli Mohamed

"Stripe" gem in rails - how to change redirect upon payment?

The Stripe gem has an inherent redirect to their "Thanks, you paid $x". How can I redirect, instead of to this "create" view, to a different route?

Thank you!



via Chebli Mohamed

Allow users to sort images based on category selected (paperclip gem) - Rails

Currently my home page (index.html.erb) shows all the user images loaded within the past 24 hours, which is part of posts. However I would like to add a form that allows the user to sort images based on their category and upload date. (For example images with the category music, uploaded within the past month) I understand how to query the database but I dont know how to take the user input. When I create a form, suing simple form: <%= simple_form_for @posts do |f| %>, it throws an error, saying I cannot use an object. Ive thought about ajax but it doesnt seem to work well with the paperclip gem, plus I rather get it done on the backend. I hope my issue well enough. If not feel free to comment as I will be around to respond. Thanks in advance.

Post Controller:
 def index  
 @posts = Post.all.where(created_at:(Time.now - 1.day)..Time.now)
 end

Schema for Post table:

create_table "posts", force: :cascade do |t|
t.string   "title"
t.string   "instagram"
t.text     "description"
t.datetime "created_at",                            null: false
t.datetime "updated_at",                            null: false
t.integer  "user_id"
t.string   "image_file_name"
t.string   "image_content_type"
t.integer  "image_file_size"
t.datetime "image_updated_at"



via Chebli Mohamed

RoR: jquery file upload on submit form button

How do I make it so my submit button will upload the images?

<%= simple_form_for @project, html: { multipart: true, id: 'fileupload' } do |f| %>

  <span class="btn btn-success fileinput-button">
    <i class="glyphicon glyphicon-plus"></i>
    <span>Add files...</span>
    <input type="file" name="photos[]" id='photo_upload_btn', multiple>
  </span>
  <button type="submit" class="btn btn-primary start">
    <i class="glyphicon glyphicon-upload"></i>
    <span>Start upload</span>
  </button>
  <button type="reset" class="btn btn-warning cancel">
    <i class="glyphicon glyphicon-ban-circle"></i>
    <span>Cancel upload</span>
  </button>

  <%= f.button :submit, class: "btn btn-primary pull-right" %>
<% end %>


<script>
$(function () {

'use strict'; //not even sure what this is for

$('#fileupload').fileupload({

});
    // Load existing files:
    $('#fileupload').addClass('fileupload-processing');
    $.ajax({
        url: $('#fileupload').fileupload('option', 'url'),
        dataType: 'json',
        context: $('#fileupload')[0]
    }).always(function () {
        $(this).removeClass('fileupload-processing');
    }).done(function (result) {
        $(this).fileupload('option', 'done')
            .call(this, $.Event('done'), {result: result});
    });
});
</script>

Right now, when I upload an image, it'll show thumbnail preview and start button with a cancel button. I want to move the start button and have it all upload using the submit button.



via Chebli Mohamed

A better way to do conditional active record statements?

I'm trying to figure out a better way to have one query here. I want to be able to send something to last where statement a wildcard so I can select all vendors. Right now if i don't include that line it doesn't filter by vendor so I essentially get all the purchase requests.

Any thoughts of a cleaner way to do these sorts of queries?

  if @vendor == "0" #checks for vendor
    @purchase_requests = PurchaseRequest.includes(:purchase_order)
                          .where(:created_at => @date_start..@date_end)
                          .where(:total_cost => @cost_beginning..@cost_end)
  else
    @purchase_requests = PurchaseRequest.includes(:purchase_order)
                          .where(:created_at => @date_start..@date_end)
                          .where(:total_cost => @cost_beginning..@cost_end)
                          .where("purchaseorder.VendorRef_ListID = ?", @vendor)
  end



via Chebli Mohamed

Add message to chat component(react.js) via websockets

Context:

I am developing a Ruby On Rails application and I started using React.js to manage my javascript components. My application provides a facebook-like chat: several chats are displayed at the bottom of the page.

Problem

I have a ChatList component that renders the chats. A chat is made of its messages and its form. When this form is submitted, an AJAX call is made to the server to POST the message and the message is added to the current chat.

this.setState({messages: this.state.messages.concat([newMessage])});

The server then broadcast Javascript code to the receiver.

This is where I'm stuck. How can I add the message to the correct chat? How can I select my React.js component and change its 'props'? When I was not using react, I used to broadcast this code to the other user:

$("#chat-<%= chat.id %>").append("<%= message.content" %>);

I guess I have to find a way to select the React component (the chat instance) and change its property "messages". How?

Thank you for your help! :)

EDIT: I'm going to add more information, just in case:

  • My ChatList is a global variable that takes an array of Chats.
  • Each Chat takes an array of Message and a form.

When I submit the form of a chat, it adds the message to the Chat (locally and it also posts the new message to the server). When the server receives the POST event, it can render javascript code to the other user.

This code should add the message to the correct Chat for the correct user. There are two pieces missing:

  1. I don't know how I can "select" the Chat.
  2. I don't know how I can add a message to the "messages" array of this Chat.


via Chebli Mohamed

my rspec output is so long it pushes the error out of view

Forgive me, I'm just trying to learn to test, but i know this is ridiculous. Anyone know what could be causing this?

I'm following along at devwalks.com and I'm on the part one of the testing track.

Failures:

  1) Creating posts Can create a job
     Failure/Error: visit '/'
     ActionView::MissingTemplate:
       Missing template posts/index, application/index with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
         * "/Users/Andy/Desktop/rails/phototest/app/views"
     # /Users/Andy/.rvm/gems/ruby-2.2.1/gems/ <-- this line repeats around 50 times with different subfolders/files 

Finished in 0.03078 seconds (files took 2.7 seconds to load)
2 examples, 1 failure, 1 pending

Failed examples:

rspec ./spec/features/creating_posts_spec.rb:4 # Creating posts Can create a job



via Chebli Mohamed

Unexpected label while trying to iterate over a ruby hash

I am in the process of trying to iterate over a ruby hash. I'll have to admit that my knowledge of ruby is very poor and i am in the process of trying to correct that, and so please bear with me if this is a very elementary question.

I am wondering if the syntax of my hash is off. The reason why it is looking the way that it is is because it is part of a rakefile, and i need to incorporate multiple addresses in this. (which i've never done, i've always only had 1 address to worry about) I know the solution to this is to build the addresses in as a rakefile, and then loop over them.

clinic.build_address.each do | build_address |
                            {
                              (city: "Minneapolis",
                              state: "MN",
                              address1: "316 10th ave",
                              zip: "55414"),
                              (city: "Hudson",
                              state: "WI",
                              address1: "119 Belmont Street",
                              zip: "54016")
                            }

With what I have right now I am getting an unexpected label (it is not liking that I have 'city:minneapolis')

Would anybody be able to take a quick look at what I have with this?



via Chebli Mohamed

Friendly_id creating duplicate slugs for multiple objects in Rails

My Rails build contains no pathnames. The application consists of two main objects: collections and items. So if I have a link: https://foo.com/foo, this could potentially identify either a collection or an item. The difference is made clear within the context and UI flow throughout the application.

My question: is there a way to have the Friendly ID gem generate unique slugs by seeing if a slug has already been taken by another object? I understand you can generate candidates so that friendly ID will not duplicate a slug for a given object, but I need friendly ID to check both existing collection slugs and item slugs before generating a new slug.

I hope that didn't sound too confusing. To re-word more concisely: is there a method available for friendly ID to check for slugs in multiple objects before generating a new slug? Thank you for your help!



via Chebli Mohamed

Slim Translation error syntax

im doing translations to Haml-Slim, i have a problem in this line:

modal-alerts data= 'target-url' = new_alert_url.gsub('jusjus.jusjus', 'jusjus'),
            'ajax-form' = "false",
            'btn-ok' = 'off',
            :title = I18n.t('common.get_new_alerts')

The error is:

_alerts_bar_housing.html.slim:9: syntax error, unexpected '=', expecting keyword_end 'ajax-form' = "false", ^ 

Any idea? Thanks!



via Chebli Mohamed

Rails Rendering Partial With a Local Variable

I need some help with a test application I am working on. I have this line repeated multiple times in my application so I decided to render it out as a partial. When I do I get an error saying that it isn't seeing the local variable. Here is what's happening:

= simple_form_for ([@user, @dogs]) do |b| 
        = render 'dogs/dogs-cats-partials/newupload', :dog => b, :user => b

Here's whats inside the partial

.form-group.required
  = b.input :title, autofocus: true, :class => "form-control", :required => false
.form-group.required
  = b.input :description, autofocus: false, :class => "form-control", :required => false

Here is the exact Error:

undefined local variable or method `b' for #<#<Class:0x007f2ae1d8a5a0>:0x007f2ae1b4dc60>

Thank you in advance for anyone who can help... been stuck on this for an hour : )



via Chebli Mohamed

I'm having this issue and it looks like I am traversing the params hash correctly in the create method of the controller, but something is wrong.

user_friendships_controller.rb

class UserFriendshipsController < ApplicationController
before_filter :authenticate_user!, only: [:new]

def new
    if params[:friend_id]
        @friend = User.find(params[:friend_id])
        @user_friendship = current_user.user_friendships.new(friend: @friend)
    else
        flash[:error] = "Friend required"
    end
rescue ActiveRecord::RecordNotFound
    render file: 'public/404', status: :not_found
end

def create
    if params[:user_friendship] && params[:user_friendship].has_key?(:friend_id)
        @friend = User.find(params[:user_friendship][:friend_id])
        @user_friendship = current_user.user_friendships.new(friend: @friend)
        @user_friendship.save
        flash[:success] = "You are now friends with #{@friend.first_name.titleize}!"
        redirect_to user_path(@friend)
    else
        flash[:error] = "Friend required"
        @user_friendship = current_user.user_friendships.new(friend: @friend)
    end
end
end

The error is on line 17 @friend = User.find(params[:user_friendship][:friend_id])

Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"p8hBlY50rLH4477juS4tAoo2aWiEaUD6oSzuCzxPTiU=",
 "user_friendship"=>{"friend_id"=>"#<User:0x007f88b1d4f9e0>"},
 "commit"=>"Yes,
 Add Friend"}



via Chebli Mohamed

I don't know why I can't display an image when I create a product using CarrierWave? I also get an error now when I want to edit my product.

I'm using Rails -v 4.2.1 & ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin14.0]

controllers/products_controller.rb

class ProductsController < ApplicationController
  before_filter :find_product, only: [:edit, :show, :update, :destroy]

  def index
    @products = Product.order("created_at DESC")
  end

  def show
  end

  def new
    @product = Product.new
  end

  def create
   @product = Product.new(product_params)

   if @product.save!
      flash[:success] = "Product created!"
      redirect_to products_path
    else
      flash[:danger] = "Error creating product."
      redirect_to new_product_path
    end
  end

  def edit
  end

  def update
    if @product.update_attributes(product_params)
      flash[:success] = "Product Updated!"
      redirect_to products_path
    else
      redirect_to "edit"
    end
  end

  private

  def product_params
    params.require(:product).permit(:name, :description, :price, :images)
  end

  def find_product
    @product = Product.find(params[:product_id])
  end
end

models/product.rb

class Product < ActiveRecord::Base
  mount_uploader :image, ImageUploader
end

uploaders/image_uploader.rb

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick

  storage :file

  def extension_white_list
    %w(jpg jpeg gif png)
  end

  version :thumb do
    process resize_to_fill: [200, 200]
  end 

  version :small_thumb, from_version: :thumb do
    process resize_to_fill: [20, 20]
  end

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



via Chebli Mohamed

Getting Select2 Gem to work with ActiveAdmin "Add New" Button

I have a RubyOnRails Application that uses the ActiveAdmin and Select2 Gems. Right now, I have made a search box that after typing two letters, shows possible options from the set given. Here is the code for that:

f.has_many :location_permissions, :allow_destroy => true, heading: 'Users With Access To This Installation' do |app_f|
  app_f.input :user,  :input_html => { :class => "user_select" }, :collection => User.all.map{ |user| ["#{user.name} (#{user.email})", user.id] }
end

This also creates an "Add New" button below. When the button is clicked, a regular ActiveAdmin dropdown menu appears, but I want the Select2 search menu created above to show up. How do I do this?

Here is the user_select function:

$('.user_select').select2({
  minimumInputLength: 2
});

If I click the add new button, so it creates a new form, save that empty field, and then refresh the page, the new form becomes the Select2 search form I want. This leads me to think that Select2 applys its JS and CSS on page load, so is it possible to load that part of the page again through AJAX or some other mechanism? I have no idea how to do so, so if anyone could point me at a resource to do something like that, I would appreciate the help.



via Chebli Mohamed

Whats a better way to add conditional input to views in rails?

I have a preview view of a page that I'm building up with a step by step form. Currently the preview view doesn't work, all it has is a default page with default text and styling. My task is to get the preview to display as a user submits the elements of the page through the form. This is what the default view would look like:

<h1>
  Worlds coolest Product
</h1>

<h3>
Buy me and make your life 10x more worthwhile! :)
</h3>

and this default text is rendered out by a partial that looks like this:

<%= render 'manage/deal_steps/deal/main_header' %>

...

My problem is that I need to replace the default text with the user submitted text if there is any but I also need to keep the default text just in case the user doesn't submit any thing. This way I will not get any errors if there is no input. Keeping it simple, Is there any way to achieve this effect without littering the view with conditional logic like this:

<h1>
  <%if retrieve_content('header')!= nil %>
  <%= retrieve_content('header')%>
  <%else%>
  Worlds coolest Product
  <% end%>
</h1>

<h3>
<%if retrieve_content('header_two')!= nil %>
  <%= retrieve_content('header_two')%>
<%else%>
Buy me and make your life 10x more worthwhile! :)
<%end%>
</h3>



via Chebli Mohamed

How to save nil into serialized attribute in Rails 4.2

I am upgrading an app to Rails 4.2 and am running into an issue where nil values in a field that is serialized as an Array are getting interpreted as an empty array. Is there a way to get Rails 4.2 to differentiate between nil and an empty array for a serialized-as-Array attribute?

Top level problem demonstration:

#[old_app]
 > Rails.version
 => "3.0.3"
 > a = AsrProperty.new; a.save; a.keeps
 => nil

#[new_app]
 > Rails.version
 => "4.2.3"
 > a = AsrProperty.new; a.save; a.keeps
 => []

But it is important for my code to distinguish between nil and [], so this is a problem.

The model:

class AsrProperty < ActiveRecord::Base
  serialize :keeps, Array
  #[...]
end

I think the issue lies with Rails deciding to take a shortcut for attribute that are serialized as a specific type (e.g. Array) by storing the empty instance of that type as nil in the database. This can be seen by looking at the SQL statement executed in each app:

[old_app]: INSERT INTO asr_properties (lock_version, keeps) VALUES (0, NULL)

Note that the above log line has been edited for clarity; there are other serialized attributes that were being written due to old Rails' behavior.

[new_app]: INSERT INTO asr_properties (lock_version) VALUES (0)

There is a workaround: by removing the "Array" declaration on the serialization, Rails is forced to save [] and {} differently:

class AsrProperty < ActiveRecord::Base
  serialize :keeps #NOT ARRAY
  #[...]
end

Allows:

 > a = AsrProperty.new; a.save; a.keeps
 => []

I'll use this workaround for now, but: (1) I feel like declaring a type might allow more efficiency, and also prevents bugs by explicitly prohibiting the wrong data type being stored (2) I'd really like to figure out the "right" way to do it, if Rails does allow it.

So: can Rails 4.2 be told to store [] as its own thing in a serialized-as-Array attribute?



via Chebli Mohamed

perfect scroll bar is not working for table

I am able to see the scrollbar but unable to scroll the content in the div.

The scroll bar is visible but unable to scroll the content I have attached screenshot of how the scroll bar is rendered.

screenshot.png enter image description here

<div style="height:auto;width:777px;overflow:hidden;margin-left:0px;" id="ios_mdata" class="contentHolder">
    <table class="table table-bordered table-hover table-condensed"  style="margin-left:23px;">
        <thead>
            <tr>
                <th>Version</th>
                <th>App Type</th>
                <th>File Size(MB)</th>
                <th>Release Date</th>
                <th>Minimum OS</th>
                <th>Avg. User Rating</th>
                <th>User Rating Count</th>
                <th>Last Updated</th>
                <th>View in Store</th>
            </tr>
        </thead>
        <tbody>
            <tr>
              <td>5.3</td>
              <td>universal</td>
              <td>12382700.0</td>
              <td>2010-11-05</td>
              <td>7.0</td>
              <td>2</td>
              <td>2</td>
              <td>2015-08-03</td>
              <td>link</td> 
            </tr>
        </tbody>
    </table>
</div>
<style type="text/css">
  .contentHolder { position:relative; margin:0px auto; padding:0px; width: 600px; height: 400px; overflow: scroll; }
  .contentHolder .content { width: 1280px; height: 620px; }
  .table { width: 1200px; }
  .spacer { text-align:center }
  .table-bordered {
    border-collapse: collapse;
  }
</style>
<script type="text/javascript">
    $("#ios_mdata").perfectScrollbar()
</script>



via Chebli Mohamed

check does memcached store mysql queries

Rails 3.2.18
memcached
dalli

I have added the line to production.rb

  config.cache_store = :dalli_store, '127.0.0.1', {:namespace => 'production'}

And I want that mysql queries will be stored in memcached.
How can I checked that queries are really in memcached.
Dump or something else?
All I found is echo stats | nc 127.0.0.1 11211 I would like to get text of mysql queries stored in memcached.

Thanks in advance.



via Chebli Mohamed

Display flash message with model validations

I have the following model validations...

  validates :event_id, :uniqueness => {:scope => :email}
  validates_format_of :email, :with => /\A[^@]+@([^@\.]+\.)+[^@\.]+\z/
  validates_presence_of :email, :first_name, :last_name

..and here is my controller...

def register_learner
    @event = Event.find(params[:event_id])
    begin
      EventRegistration.create! first_name: params[:first_name], last_name: params[:last_name], email: params[:email], event_id: params[:event_id]
      rescue ActiveRecord::RecordInvalid => e
    end
end

This codes work, but the problems is it silently catches the errors. I'd like to display a flash message to the user and in the current page. So I tried this...

   def register_learner
    @event = Event.find(params[:event_id])
    begin
      @registation = EventRegistration.create! first_name: params[:first_name], last_name: params[:last_name], email: params[:email], event_id: params[:event_id]
      rescue ActiveRecord::RecordInvalid => e
      if !@registation.valid?
        flash[:notice] = @registation.errors
      end
    end
   end

...but I get the message undefined method `valid?' for nil:NilClass if the validation fails.



via Chebli Mohamed

Rails Shippo Rates

I am new to using AJAX with rails and would like to display shipping rates via Shippo and AJAX. I am successfully going through the process of creating the rates in the console, but having trouble getting those rates to display so that my users can select their desired shipping rate/price.

Any examples or recommendations?



via Chebli Mohamed

Push to Git using Rugged

I worked in a script to push to git using a script, so I choose Rugged to do that, my probleme when I try to push to repo, it gives me error, Can you help me ?

require 'rugged'


git_email = 'ettaheri.nizar@gmail.com'
git_name = 'Nizar'
repo_name = '/Users/euphor/Desktop/test/testignore1'


repo = Rugged::Repository.new('/Users/euphor/Desktop/test/testignore1')
puts "1"
index = repo.index
puts "3"

oid = repo.write("This is a blob.", :blob)

index.add(:path => "testignore1", :oid => oid, :mode => 0100644)
puts "4"

options = {}
options[:tree] = index.write_tree(repo)
puts "5"
options[:author] = { :email => git_email, :name => git_name, :time => Time.now }
options[:committer] = { :email => git_email, :name => 'Test Author', :time => Time.now }
puts "6"
options[:message] ||= "Making a commit via Rugged!"
options[:parents] = repo.empty? ? [] : [ repo.head.target ].compact
options[:update_ref] = 'HEAD'
puts "7"
Rugged::Commit.create(repo, options)
puts "8"
**repo.push 'origin'**  # this is my error
puts "Done"

the message of my error is :

/Library/Ruby/Gems/2.0.0/gems/rugged-0.23.0/lib/rugged/repository.rb:224:in push': Unsupported URL protocol (Rugged::NetworkError) from /Library/Ruby/Gems/2.0.0/gems/rugged-0.23.0/lib/rugged/repository.rb:224:in push' from vips.rb:43:in `'



via Chebli Mohamed

You have already activated rack 1.6.0, but your Gemfile requires rack 1.6.4

Similar to problem with rack 1.3.2. You have already activated rack 1.3.2, but your Gemfile requires rack 1.2.3 -- I'm experiencing You have already activated rack 1.6.0, but your Gemfile requires rack 1.6.4 when attempting to run Rails (4.2) in production with Puma and Nginx.

bundle update rake nor rm Gemfile.lock && bundle install seem to help, the only solution I have so far is manually changing rack (1.6.4) to rack (1.6.0) in Gemfile.lock.



via Chebli Mohamed

Travis CI command is not available from console

I've installed the travis gem

gem install travis

Gem was installed successful, but travis login is not available from console (Ubuntu). Output tells that travis application is not installed and I can install it with sudo apt-get install travis. But it's not that Travis CI I need.



via Chebli Mohamed

Issue saving images with PaperClip on rails

Hoping you can help with me an issue I'm currently having.

I've set up Paperclip to help me with image uploading and after following instructions and checking various guides, I believe it should be working, but I am running into an issue where it's simply not saving the image and displaying the following error. Can anyone point a learner in the right direction?

I've used imagemagick to convert via the command line without any issues.

UPDATE: I've just looked through my files again and found that I've added this as it asked in the documentation. Do I need to amend the :command_path

UPDATE 2: I have fixed the issue now and my resolution is the answer section belo.

Paperclip.options[:command_path] = "/usr/local/bin/"

.

There was an error processing the thumbnail for f87ef1d19d0a3693810436f1278205e020150803-666-1avrc9e

The extracted source is as follows:

def create
admin = Admin.new(admin_params)

if admin.save
  redirect_to '/administration'

Parameters

{"utf8"=>"✓",
 "authenticity_token"=>"lZ9kDGwvbTUTElcOkKPrgpmiX9HlIfVpAXyRROk/jcRdoGJX9/unlBx6SuazNa9BXw0UIJhbmJiSUVin4DrsBg==",
 "admin"=>{"name"=>"fffsfdsa",
 "email"=>"dfsdfsfadsafsd@gmail.com",
 "user_name"=>"hjdfkhasdjhasjfdkh",
 "password"=>"[FILTERED]",
 "password_confirmation"=>"[FILTERED]",
 "avatar"=>#<ActionDispatch::Http::UploadedFile:0x007f9082386cf0 @tempfile=#<Tempfile:/var/folders/t6/jrprg2rd57zch5mkt5cg_5cr0000gn/T/RackMultipart20150803-666-1crp2va.jpg>,
 @original_filename="image_name.jpg",
 @content_type="image/jpeg",
 @headers="Content-Disposition: form-data; name=\"admin[avatar]\"; filename=\"image_name.jpg\"\r\nContent-Type: image/jpeg\r\n">},
 "commit"=>"Submit"}

Model (admin.rb)

class Admin < ActiveRecord::Base
has_secure_password

has_attached_file :avatar, :styles => {
    :medium => "300x300>",
    :thumb => "50x50#>"},
    :default_url => "/images/:style/missing.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
end

Admin Controller

 class AdminController < ApplicationController
def new
end

def create
admin = Admin.new(admin_params)

if admin.save
  redirect_to '/administration'
  flash[:success] = "Admin account created successfully"
else
    flash[:error] = "Unable to create account"
  render 'administration/new_ai_admin'
end
end

private

def admin_params
params.require(:admin).permit(:name, :email, :user_name, :password, :password_confirmation, :avatar)
end
end



via Chebli Mohamed

Rails routes: Wrong singular for resources

I have the following line in my routes.rb (Rails 4.1.4):

resources :request_caches

However, when I run rake routes I get the following output:

request_caches    GET    /request_caches(.:format)            request_caches#index
                  POST   /request_caches(.:format)            request_caches#create
new_request_cach  GET    /request_caches/new(.:format)        request_caches#new
edit_request_cach GET    /request_caches/:id/edit(.:format)   request_caches#edit
request_cach      GET    /request_caches/:id(.:format)        request_caches#show
                  PATCH  /request_caches/:id(.:format)        request_caches#update
                  PUT    /request_caches/:id(.:format)        request_caches#update
                  DELETE /request_caches/:id(.:format)        request_caches#destroy

As you can see, Rails somehow maps request_caches plural to request_cach singular. But it should be request_cache. Is this some kind of special case, because of the word caches? I've also played around with

resources :request_caches, as: :request_cache

But this results in wrong routes like request_cache_index. And furthermore, I think this is a standard task and should be solved clearly using Rails intern route helpers.

So, what am I doing wrong?



via Chebli Mohamed

Using def_delegate with a hash

I know how Forwardable#def_delegate works with methods on objects, but is there a similar way to forward methods names to hash keys. Like:

hash = { some_value: 42, other_value: 31415 }
def_delegate :hash, :some_value, :other_value

Calling object.some_value should return 42

PS: def and class eval is a way, but is there a nicer way?



via Chebli Mohamed

how do we encode each byte as two hexadecimal characters in ruby?

I have a hexadecimal number as

hexMidAppId = '0001000000000002'

In node.js, we have a library new Buffer(hexMidAppId, 'hex') which gives me the output as

<Buffer 00 01 00 00 00 00 00 02>

now the same output i want to get it in ruby but i couldn't find any equivalent method in ruby for the Buffer method. Can anyone help me this?



via Chebli Mohamed

Javascript gem "format.js"

I want to upload file with javascript AJAX but I have an error InvalidAuthenticutyToken when I correct my code like I see on many website another error appear : Unknown format in :

if @personal.save
    format.js
end

In my IDE the .js do an error : cannot find js

I think I miss a gem. My installed gems in order to use javascript are :

gem 'coffee-rails',          '~> 4.1.0'
gem 'coffee-script-source',  '1.8.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder',              '~> 2.0'

And my form is

<%= bootstrap_form_for @personal, :html => {:multipart => true}, :remote => true do |f| %>
<div class="modal-body">
  <%= f.text_field :trigramme, label: "Trigramme" %>
  <%= f.text_field :nom, label: "Nom" %>
  <%= f.text_field :prenom, label: "Prenom" %>
  <%= f.text_field :poste, label: "Poste" %>
  <%= f.text_field :arrivee, label: "Arrivee a OCTO" %>
  <%= f.text_area :bio, label: "Bio", :rows => "5" %>
  <%= f.file_field :img, label: "Photo" %>

</div>
<div class="modal-footer">
  <%= f.submit class: "btn btn-primary" %>
  <%= link_to "Cancel", "#", class: "btn", data: {dismiss: "modal"} %>
</div>

It's weird because when I have the error of Invalid AuthenticutyToken my image is correctly uploaded in database but I have the error. I have some js.erb file that print a popup with the form. I have tried remotipart but nothin happen I have again the error.

Do I miss a gem in order to use javascript due to second error unknownFormat? What is my problem ? Do you have a clue?



via Chebli Mohamed

In rails, the instance of the model doesn't show up in my table. What is happening when the console says "COMMIT" and "=>true"?

I am pretty new to Ruby on Rails and I'm having some problems. I have already checked out: This stackoverflow question about cloning a model

I am creating a new method for a model that looks like this:

def copy(new_period)
@copy = self.clone
@copy.report_id = Report.maximum(:report_id).next
@copy.period_id = new_period
@copy.save
end

I am trying to create a new instance of report that can be moved to the next year(period). When I run this method in irb I get:

irb(main):003:0> c = r.copy(5)

(1.8ms) SELECT MAX("reports"."report_id") AS max_id FROM "reports"

(0.8ms) BEGIN

(1.0ms) UPDATE "reports" SET "period_id" = 5 WHERE "reports"."report_id" = 438

(1.1ms) COMMIT

=> true

When I look in pgAdmin the new report isn't there. Could someone please explain to me what is going on when the console says "commit" and "=> true"? Does this not mean it has saved to the database?



via Chebli Mohamed

Rails 3: Displaying conversation list and selected conversation on the same page (using Mailboxer)

Framework: Rails 3/ Jruby with Mailboxer gem.

I want to create a Facebook style inbox page that allows a user to scroll through their Inbox, Sent Items and Trash, whilst keeping the selected conversation displayed on the right hand side of the page (like Facebook's implementation of the desktop inbox)

The action of clicking the conversation title should render that entire conversation to the right side of the page, avoiding the need of dedicating an entire page to one conversation within the web browser. This is so (in a later version) I can implement an AJAX call that will only refresh the conversation part of the page, whilst allowing the user to keep an eye on their conversation list.

My problem is, I'm completely stumped as to how this would be implemented, without the routing error No route matches [GET] "/conversations/20/show_conversation" that I'm currently getting. I'm fairly new to Ruby on Rails, so the whole routing side of things is a bit confusing.

My question how do I display all my conversations, as well as the transcript of one selected conversation (at any given time) on the same page. Preferably, I would like to avoid the use of Javascript/ jQuery and stick to the Ruby on Rails implementation, if possible.

Here's a screenshot of my "messages" page, where "Conversation.." (on the right) should display the transcript of the conversation I had with the target user.

enter image description here

My controller code for the current page:

class ConversationsController < ApplicationController
    before_filter :authenticate_user!
    before_filter :get_mailbox
    before_filter :get_conversation, except: [:index]
    before_filter :get_box, only: [:index]
    before_filter :get_conversation, except: [:index, :empty_trash]

    def index
        @conversations = @mailbox.inbox.paginate(page: params[:page], per_page: 10)
        @inbox = @mailbox.inbox.paginate(page: params[:page], per_page: 10)
        @trash = @mailbox.trash.paginate(page: params[:page], per_page: 10)
        @sent = @mailbox.sentbox.paginate(page: params[:page], per_page: 10)
    end

    def show_conversation
        @conversation
        redirect_to conversations_path
    end 

    [...]

    private 

    def get_mailbox
        @mailbox ||= current_user.mailbox
    end

    def get_conversation 
        @conversation ||= @mailbox.conversations.find(params[:id])
    end

    def get_box
        if params[:box].blank? or !["inbox","sent","trash"].include?(params[:box])
            params[:box] = 'inbox'
        end
        @box = params[:box]
    end
end

My corresponding views: index.html.erb

<% page_header "Your Conversations" %>

<p><%= link_to 'Start conversation', new_message_path, class: 'btn btn-lg btn-primary' %> 
<%= link_to 'Empty trash', empty_trash_conversations_path, class: 'btn btn-danger', 
    method: :delete, data: {confirm: 'Are you sure?'} %></p>

<!-- tab things, they're awesome -->
<div class="left_col">
  <div class="col-sm-3">
    <ul class="nav nav-pills">
      <%= mailbox_section 'inbox', @box %>
      <%= mailbox_section 'sent', @box %>
      <%= mailbox_section 'trash', @box %>
    </ul>
  </div>

  <!-- this working part isn't in the tutorial -->
  <% if @box == 'trash' %>
    <%= render partial: 'conversations/conversation', collection: @trash %>
  <% elsif @box == 'inbox' %>
    <%= render partial: 'conversations/conversation', collection: @inbox %>
  <% elsif @box == 'sent' %>
   <%= render partial: 'conversations/conversation', collection: @sent %>
  <% end %>   
  <%= will_paginate %>
</div>

<div class="right_col"> 
  <p><small>Conversation...</small></p>
  <%= @conversation %> <!-- should I have a partial or something? -->
</div>

_conversation.html.erb partial where the link to show_conversation is

<%= link_to conversation.subject,   show_conversation_conversation_path(conversation) %>

<div class="btn-group-vertical pull-right">
    <% if conversation.is_trashed?(current_user) %>
        <%= link_to 'Restore', restore_conversation_path(conversation),
                         class: 'btn btn-xs btn-info', method: :post %>
    <% else %>
        <%= link_to 'Move to trash', conversation_path(conversation), 
                         class: 'btn btn-xs btn-danger', method: :delete,
                  data: {confirm: 'Are you sure?'} %>

        <% if conversation.is_unread?(current_user) %>
            <%= link_to 'Mark as read', mark_as_read_conversation_path(conversation), 
                    class: 'btn btn-xs btn-info', method: :post %>
        <% end %>
    <% end %>
</div>

<p><%= render 'conversations/participants', conversation: conversation %></p>

<p><%= conversation.last_message.body %>
  <small>(<span class="text-muted">
<%= conversation.last_message.created_at.strftime("%-d %B %Y, %H:%M:%S") %>
</span>)</small></p>

And finally, my routes.rb

resources :conversations, only: [:index, :show, :destroy] do
    member do
        post :reply, :restore, :mark_as_read, :show_conversation
    end

    collection do 
        delete :empty_trash
    end
end

resources :messages, only: [:new, :create]

root :to => 'conversations#index'

I do have a working conversation partial that builds the conversation on a separate page. It works fine, but I haven't included it because I want to move away from having a separate page to view the conversation. Any help on this would be greatly appreciated!

Thanks,



via Chebli Mohamed

How can I get zbar to deploy on Heroku?

I am using the ruby-zbar gem in a rails app to scan barcodes from jpgs. I installed the zbar library using homebrew on my local machine and everything works fine. However, when deploying to Heroku I consistently get errors such as the following:

remote:        LoadError: Didn't find libzbar on your system
remote:        Please install zbar (http://ift.tt/refsyg) or set ZBAR_LIB if it's in a weird place
remote:        FFI::Library::ffi_lib() failed with error: library names list must not be empty

I've tried following the advice from this Stack Overflow post (Heroku Zbar Didn't find libzbar on your system (LoadError)), namely to set the ZBAR_LIB ENV variable to /app/vendor/lib/libzbar.so, or failing that to run heroku bash and try to find a file named libzbar.so and point ZBAR_LIB to its path.

However, I can't seem to find the heroku buildpack referenced in the original Stack Overflow post (the link to http://ift.tt/1mpaR2J goes to a 404 page), so I can't replicate the solution outlined there.

I have tried all of the following buildpacks:

http://ift.tt/1ImOq5Q
http://ift.tt/1KO1BT3
http://ift.tt/1ImOsdY

During the build process I can see hopeful messages like this:

remote: -----> Multipack app detected
remote: -----> Fetching custom git buildpack... done
remote: -----> ZBAR app detected
remote: -----> Downloading and installing ZBAR
remote: -----> Configuring ZBAR
remote: -----> Make!
remote: -----> Make install !!!
remote: -----> Writing profile script
remote: -----> Fetching custom git buildpack... done
remote: -----> Ruby app detected
remote: -----> Compiling Ruby/Rails
remote: -----> Using Ruby version: ruby-2.2.1

But setting ZBAR_LIB to /app/vendor/lib/libzbar.so gives me some version of this error:

remote:        LoadError: Didn't find libzbar on your system
remote:        Please install zbar (http://ift.tt/refsyg) or set ZBAR_LIB if it's in a weird place
remote:        FFI::Library::ffi_lib() failed with error: Could not open library '/app/vendor/lib/libzbar.so': /app/vendor/lib/libzbar.so: cannot open shared object file: No such file or directory

And trying to find libzbar.so on heroku run bash has not been successful for me -- I can see many files that are similar in name (even a libzbar.rc) but none that fits the bill.

~ $ find / -name '*libzbar*'
find: `/var/lib/polkit-1': Permission denied
/app/vendor/zbar/plugin/.deps/plugin_libzbarplugin_la-plugin.Plo
/app/vendor/zbar/qt/.deps/qt_libzbarqt_la-QZBar.Plo
/app/vendor/zbar/qt/.deps/qt_libzbarqt_la-QZBarThread.Plo
/app/vendor/zbar/qt/.deps/qt_libzbarqt_la-moc_QZBarThread.Plo
/app/vendor/zbar/qt/.deps/qt_libzbarqt_la-moc_QZBar.Plo
/app/vendor/zbar/gtk/.deps/gtk_libzbargtk_la-zbargtk.Plo
/app/vendor/zbar/gtk/.deps/gtk_libzbargtk_la-zbarmarshal.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-symbol.lo
/app/vendor/zbar/zbar/zbar_libzbar_la-video.o
/app/vendor/zbar/zbar/zbar_libzbar_la-error.lo
/app/vendor/zbar/zbar/processor/zbar_libzbar_la-lock.lo
/app/vendor/zbar/zbar/processor/.libs/zbar_libzbar_la-lock.o
/app/vendor/zbar/zbar/processor/zbar_libzbar_la-lock.o
/app/vendor/zbar/zbar/processor/.deps/zbar_libzbar_la-null.Plo
/app/vendor/zbar/zbar/processor/.deps/zbar_libzbar_la-x.Plo
/app/vendor/zbar/zbar/processor/.deps/zbar_libzbar_la-posix.Plo
/app/vendor/zbar/zbar/processor/.deps/zbar_libzbar_la-lock.Plo
/app/vendor/zbar/zbar/processor/.deps/zbar_libzbar_la-win.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-config.o
/app/vendor/zbar/zbar/zbar_libzbar_la-processor.o
/app/vendor/zbar/zbar/zbar_libzbar_la-refcnt.lo
/app/vendor/zbar/zbar/zbar_libzbar_la-convert.o
/app/vendor/zbar/zbar/zbar_libzbar_la-video.lo
/app/vendor/zbar/zbar/zbar_libzbar_la-window.o
/app/vendor/zbar/zbar/video/.deps/zbar_libzbar_la-null.Plo
/app/vendor/zbar/zbar/video/.deps/zbar_libzbar_la-v4l1.Plo
/app/vendor/zbar/zbar/video/.deps/zbar_libzbar_la-v4l2.Plo
/app/vendor/zbar/zbar/video/.deps/zbar_libzbar_la-vfw.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-processor.lo
/app/vendor/zbar/zbar/zbar_libzbar_la-image.lo
/app/vendor/zbar/zbar/zbar_libzbar_la-refcnt.o
/app/vendor/zbar/zbar/zbar_libzbar_la-error.o
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-qrdectxt.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-binarize.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-isaac.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-rs.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-qrdec.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-bch15_5.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-util.Plo
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-video.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-config.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-processor.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-convert.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-window.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-refcnt.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-error.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-img_scanner.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-image.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-symbol.o
/app/vendor/zbar/zbar/zbar_libzbar_la-img_scanner.o
/app/vendor/zbar/zbar/zbar_libzbar_la-image.o
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-null.Plo
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-dib.Plo
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-xv.Plo
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-x.Plo
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-ximage.Plo
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-win.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-img_scanner.lo
/app/vendor/zbar/zbar/libzbar.rc
/app/vendor/zbar/zbar/zbar_libzbar_la-symbol.o
/app/vendor/zbar/zbar/zbar_libzbar_la-config.lo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-decoder.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-config.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-convert.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-processor.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-symbol.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-scanner.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-error.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-jpeg.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-video.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-window.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-refcnt.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-svg.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-img_scanner.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-image.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-window.lo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-code39.Plo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-pdf417.Plo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-qr_finder.Plo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-i25.Plo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-ean.Plo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-code128.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-convert.lo

Has anyone had success getting zbar to run on heroku? If so, what buildpack did you use? I would be thrilled to learn how to make this work.



via Chebli Mohamed

Elasticsearch stops after import data from model

  1. I deployed my app to vps.
  2. Started Elasticsearch, and checked it with ps aux | grep elasticsearch
  3. cd app/currect && RAILS_ENV=production bin/rails c
  4. User.import

    Output:

    Scoped order and limit are ignored, it's forced to be batch order and batch size  
      User Load (0.4ms)  SELECT "users".* FROM "users"  ORDER BY "users"."id" ASC LIMIT 10
    Faraday::ConnectionFailed: connection refused: localhost:9200
    
    
  5. Elasticsearch stopped and import doesn't work, why ?

I am using Ubuntu 14, Puma server, SQLite database. Does it matter?

Additional notes:

http://ift.tt/1P3OOuv - gemfile.lock from project

http://ift.tt/1IVORti - elasticsearch config

http://ift.tt/1P3OOux - elasticsearch log

Before User.import

ps aux | grep elasticsearch

shows elasticsearch process

After User.import ps aux | grep elasticsearch doesn't show process

How to check if elasticsearch uses 9200 port ?



via Chebli Mohamed

Ruby- web api with rest client gem

I'm new in Ruby (and in developing too) and I would like to get the response from another url (my url) in the get method.

i'm using rest-client gem.

I have tried this code:

class UsersController < ApplicationController require 'rest-client' def index

RestClient::Request.execute( method: :get, url: 'https://my-url')

end

end

but when I open http://localhost:3000/users I get a blank page

Thanks in advance,

Joel



via Chebli Mohamed

Can't upload PDF using carrierwave on Heroku?

In my rails 4 app, I'm using carrierwave to upload files to google cloud storage. I'm able to successfully upload image files, but pdfs are not working. It shows following error:

You are not allowed to upload "pdf" files, allowed types: jpg, jpeg, gif, png

Here is my uploader:-

# encoding: utf-8
require 'carrierwave/processing/mime_types'
class AttachmentUploader < CarrierWave::Uploader::Base

  include CarrierWave::MiniMagick
  include CarrierWave::MimeTypes

  storage :fog

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

  process :set_content_type

  def extension_white_list
    %w(jpg jpeg gif png pdf)
  end

end

I don't know what's wrong with this code.

And here's the attachment model

class Attachment < ActiveRecord::Base
  mount_uploader :attachment, AttachmentUploader

  # Associations

  belongs_to :attached_item, polymorphic: true

  # Validations

  validates_presence_of :attachment
  validates_integrity_of :attachment

  # Callbacks

  before_save :update_attachment_attributes

  # Delegate

  delegate :url, :size, :path, to: :attachment

  # Virtual attributes

  alias_attribute :filename, :original_filename

  private

  def update_attachment_attributes
    if attachment.present? && attachment_changed?
      self.original_filename = attachment.file.original_filename
      self.content_type = attachment.file.content_type
    end
  end
end

Update: When testing on local machine it works but not on heroku. On development env it works without issue and I can check file uploaded to google storage. But on heroku it displays error "You are not allowed to upload "pdf" files, allowed types: jpg, jpeg, gif, png"

Thanks in advance!



via Chebli Mohamed