mercredi 30 septembre 2015

actionview-4.2.4 - uninitialized constant ActionView::Helpers::ActiveModelHelper (NameError)

C:\Users\Clarion Smith\Documents\Sites\simple_cms>rails server
C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.4/lib/action_view/helpers.rb:40:in `<module:Helpers>': uninitialized constant ActionView::Helpers::ActiveModelHelper (NameError)
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.4/lib/action_view/helpers.rb:4:in `<module:ActionView>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-4.2.4/lib/action_view/helpers.rb:3:in `<top (required)>'
        from C:/Ruby22/lib/ruby/gems/2.2.0/gems/actionview-

My problem is very common in Ruby and Rails. Though I went through different stackoverflow answers, I could not find anything specific which would fix my error.

I tried reinstalling lower version of the railites gem but the same error keeps popping. I tried reinstalling all the gems that were throwing errors and still the problem doesnt seem to go away. Many articles indicated that this is a compatibility issue. But when I tried reinstalling a lower version of the railties gem(4.0.0), the command prompt still asked me to upgrade to the latest version in order to continue. I also installed 'Passenger' web server to check the compatibility and a similar error popped up but this time with the passenger gem. Please look into this accordingly. I am also copying below the gem file.

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.4'
# Use mysql as the database for Active Record
gem 'mysql2'
#Bundle for Passenge r web server
gem 'passenger'
# Use SCSS for stylesheets
#gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets

#gem 'uglifier', '>= 1.3.0'
gem 'rack', '~> 1.6.0'
gem 'rspec-rails', :group => [:development, :test]
# Use CoffeeScript for .coffee assets and views

#gem 'coffee-rails', '~> 4.1.0'
# See http://ift.tt/1D4cmMg for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library

#gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: http://ift.tt/OVlBaz

#gem 'turbolinks'
# Build JSON APIs with ease. Read more: http://ift.tt/GXyveo

#gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.

#gem 'sdoc', '~> 0.4.0', group: :doc

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug'
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Specifying target path in Gemfile for bundler

I'm trying to fetch a gem from remote source and then extract it into vendor/engines

Is there a way to do this using bundler and Gemfile? Is there a way to specify target directory for a gem?

Cucumber not working when running rake cucumber

I have no features in a test app that I downloaded. I have written no code yet. I ran rake cucumber to test if it is working correctly or not and it gave me the following errors.

/home/user/.rvm/gems/ruby-2.2.1/gems/activesupport-3.2.18/lib/active_support/values/time_zone.rb:270: warning: circular argument reference - now
/home/user/.rvm/rubies/ruby-2.2.1/bin/ruby -S bundle exec cucumber  --profile default
/home/user/.rvm/gems/ruby-2.2.1/gems/cucumber-1.3.15/lib/cucumber/ast/step.rb:80: warning: circular argument reference - name
/home/user/.rvm/gems/ruby-2.2.1/gems/activesupport-3.2.18/lib/active_support/values/time_zone.rb:270: warning: circular argument reference - now
cannot load such file -- test/unit (LoadError)
/home/user/.rvm/gems/ruby-2.2.1/gems/activesupport-3.2.18/lib/active_support/dependencies.rb:251:in `require'
/home/user/.rvm/gems/ruby-2.2.1/gems/activesupport-3.2.18/lib/active_support/dependencies.rb:251:in `block in require'
/home/user/.rvm/gems/ruby-2.2.1/gems/activesupport-3.2.18/lib/active_support/dependencies.rb:236:in `load_dependency'
/home/user/.rvm/gems/ruby-2.2.1/gems/activesupport-3.2.18/lib/active_support/dependencies.rb:251:in `require'
/home/user/.rvm/gems/ruby-2.2.1/gems/railties-3.2.18/lib/rails/test_help.rb:5:in `<top (required)>'
/home/user/.rvm/gems/ruby-2.2.1/gems/activesupport-3.2.18/lib/active_support/dependencies.rb:251:in `require'
/home/user/.rvm/gems/ruby-2.2.1/gems/activesupport-3.2.18/lib/active_support/dependencies.rb:251:in `block in require'
/home/user/.rvm/gems/ruby-2.2.1/gems/activesupport-3.2.18/lib/active_support/dependencies.rb:236:in `load_dependency'
/home/user/.rvm/gems/ruby-2.2.1/gems/activesupport-3.2.18/lib/active_support/dependencies.rb:251:in `require'
/home/user/.rvm/gems/ruby-2.2.1/gems/cucumber-rails-1.4.1/lib/cucumber/rails.rb:11:in `<top (required)>'
/home/user/SE/bdd-tdd-cycle/rottenpotatoes/features/support/env.rb:7:in `require'
/home/user/SE/bdd-tdd-cycle/rottenpotatoes/features/support/env.rb:7:in `<top (required)>'
/home/user/.rvm/gems/ruby-2.2.1/gems/cucumber-1.3.15/lib/cucumber/rb_support/rb_language.rb:95:in `load'
/home/user/.rvm/gems/ruby-2.2.1/gems/cucumber-1.3.15/lib/cucumber/rb_support/rb_language.rb:95:in `load_code_file'
/home/user/.rvm/gems/ruby-2.2.1/gems/cucumber-1.3.15/lib/cucumber/runtime/support_code.rb:180:in `load_file'
/home/user/.rvm/gems/ruby-2.2.1/gems/cucumber-1.3.15/lib/cucumber/runtime/support_code.rb:83:in `block in load_files!'
/home/user/.rvm/gems/ruby-2.2.1/gems/cucumber-1.3.15/lib/cucumber/runtime/support_code.rb:82:in `each'
/home/user/.rvm/gems/ruby-2.2.1/gems/cucumber-1.3.15/lib/cucumber/runtime/support_code.rb:82:in `load_files!'
/home/user/.rvm/gems/ruby-2.2.1/gems/cucumber-1.3.15/lib/cucumber/runtime.rb:184:in `load_step_definitions'
/home/user/.rvm/gems/ruby-2.2.1/gems/cucumber-1.3.15/lib/cucumber/runtime.rb:42:in `run!'
/home/user/.rvm/gems/ruby-2.2.1/gems/cucumber-1.3.15/lib/cucumber/cli/main.rb:47:in `execute!'
/home/user/.rvm/gems/ruby-2.2.1/gems/cucumber-1.3.15/bin/cucumber:13:in `<top (required)>'
/home/user/.rvm/gems/ruby-2.2.1/bin/cucumber:23:in `load'
/home/user/.rvm/gems/ruby-2.2.1/bin/cucumber:23:in `<main>'
/home/user/.rvm/gems/ruby-2.2.1/bin/ruby_executable_hooks:15:in `eval'
/home/user/.rvm/gems/ruby-2.2.1/bin/ruby_executable_hooks:15:in `<main>'

Could someone tell me what's going on? And what is the solution to this problem? It should ideally output that there are no tests available and the 0/0 steps passed.

Rails gem - Public Activity for earlier posts

The gem does not recognize earlier post which were created before the gem was added. It only started working, when fresh posts were created. Why was that?

And, how to have those earlier posts get covered by public_activity

Thanks.
Gem setup according to author site.

Generate model in ruby on rails not doing anything and even not showing any error

This is my application.rb file context. I am not sure but I think there is some problem regarding active_record though there is no error and generate model just show "dl is deprecated please use fiddle" ! That's it! Nothing else and no migration file is created.


Rails.application.configure

do
  # Settings specified here will take precedence over those in config/application.rb.

  # In the development environment your application's code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports and disable caching.
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = false

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations.


  # Debug mode disables concatenation and preprocessing of assets.
  # This option may cause significant delays in view rendering with a large
  # number of complex assets.
  config.assets.debug = true

  # Adds additional error checking when serving assets at runtime.
  # Checks for improperly declared sprockets dependencies.
  # Raises helpful error messages.
  config.assets.raise_runtime_errors = true

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true
end

Rails - Uploading large files directly to S3 with Jquery File Upload (hosted on Heroku )

I'm using Heroku, which means I have to upload multiple large files to S3 directly.. I'm using Rails 3.2.11, and Ruby 1.9.3. I do not wish to use carrierwave or paperclip gems, or really change much at this point - I just need to get this what I have working.

Before trying to move to S3, if I ran my app locally, I could upload multiple large files to the local file system. When I ran it on Heroku, small files upload but large ones failed. Hence the switch to S3..

I tried several tweaks, and also this link below, but it's just too much of a change to what I have that already working with the local server's file system (and Heroku as well, but Heroku just can't handle large files ..)

Tried: http://ift.tt/1rlOGxv

I've tried some of the other examples here on Stack Overflow but they are too much of a change for what works locally, and well, I don't grasp everything they are doing.

Now, what happens when I do try to upload images?

It's as if the file upload works - the preview images are successfully created, but nothing is ever uploaded to Amazon s3, and I don't receive any kind of error messages (like s3 authentication failure or anything.. nothing)

What do I need to change in order to get the files over to my s3 storage, and what can I write out to console to detect problems, if any, connecting to my s3?

My form:

        <%= form_for @status  do |f| %>

        {A FEW HTML FIELDS USED FOR A DESCRIPTION OF THE FILES - NOT IMPORTANT FOR THE QUESTION}

        File:<input id="fileupload"  multiple="multiple"  name="image" 
            type="file"  data-form-data = <%= @s3_direct_post.fields%> 
            data-url= <%= @s3_direct_post.url %> 
            data-host =<%=URI.parse(@s3_direct_post.url).host%> >   
        <%= link_to 'submit', "#", :id=>'submit' , :remote=>true%>

        <% end %>

My jquery is:

....
  $('#fileupload').fileupload({
      formData: {
                 batch: createUUID(),
                  authenticity_token:$('meta[name="csrf-token"]').attr('content')
                    },
      dataType: 'json',
      acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
              maxFileSize: 5000000, // 5 MB
              previewMaxWidth: 400,
              previewMaxHeight: 400,
              previewCrop: true,
      add: function (e, data) {

      tmpImg.src = URL.createObjectURL(data.files[0]) ; // create image preview 
      $('#'+ fn + '_inner' ).append(tmpImg);

    ...

My controller:

def index
#it's in the index just to simplify getting it working 

 @s3_direct_post = S3_BUCKET.presigned_post(key: "uploads/#{SecureRandom.uuid}/${filename}", success_action_status: '201', acl: 'public-read')

end

The element that is generated for the form is (via Inspect Element):

        <input id="fileupload" multiple="multiple" name="image" 
    data-form-data="{&quot;key&quot;=>&quot;uploads/34a64607-8d1b-4704-806b-159ecc47745e/${filename}&quot;," &quot;success_action_status&quot;="
    >&quot;201&quot;," &quot;acl&quot;=">&quot;public-read&quot;," &quot;policy&quot;=">&quot;[encryped stuff - no need to post]&quot;,"
     &quot;x-amz-credential&quot;=">&quot;
[AWS access key]/[some number]/us-east-1/s3/aws4_request&quot;
," &quot;x-amz-algorithm&quot;=">&quot;AWS4-HMAC-SHA256&quot;
," &quot;x-amz-date&quot;=">&quot;20150924T234656Z&quot;
," &quot;x-amz-signature&quot;=">&quot;[some encrypted stuff]&quot;}"
data-url="http://ift.tt/1gSMJ8C" data-host="nunyabizness.s3.amazonaws.com" type="file">

Help!

Hashtagging system and autosort

I am stuck with a problem to implement a feature in a photo social app which I am learning to build.

I was wondering of adding a hashtag system to captions. The model scans it, create collections automagically and through a separate controller and display like an album and also have the ability of searching for all photos of all users matching that tags.

I got stuck on the first part of it, scanning for tags and storing it somewhere. I created a new app having post with hashtags and trying to scan through regex - "post.scan(/\B#\w\w+/)".

Thats all I could progress. Coudn't use it anywhere in the controller or model, it keeps saying MoMethod error "scan".

After that how can I store that array somewhere and do rest of the work - which is mostly like a common tagging system.

Model Class name is Photo having attributes - post and hashtag.

def hashtag(post)
hashtag_regex = /\B#\w\w+/
@show = post.scan(hashtag_regex)
end

Controller

def index
@post = Photo.all
@show = Photo.hashtag(@post)
end

Rails, route time has to be greater than the time between two stops

I need some help here with a restriction in Rails. I created a transport site and the duration of the whole route should be greater than the time between two stops. This is my model file 'section.rb'

section.rb

class ValidatoreOffset < ActiveModel::Validator
    def validate(record)
        if record.controllo_offset
            record.errors[:base] << 'Error! Orario fermate intermedie maggiore dell orario della tratta di percorrenza'
        end
    end
end




class Section < ActiveRecord::Base
    has_many :departures
    has_many :reservations
    has_many :stops
    attr_accessible :travel_time, :location_arrival, :type_of_section, :start_location, :id, :id_departure, :stop_id
    validates :type_of_section, inclusion: { in: %w(festivo feriale scolastico giornaliero)} , :allow_nil => false
    delegate :offset, :to => :stop, prefix: true, :allow_nil => true

    validates_with ValidatoreOffset

    def controllo_offset
        if section.stop.offset >= section.travel_time
            return true
        end 
    end

end

offset is an attribute of Stop that indicates the time between two stops. What is wrong with that?

Rails 3 before_destroy triggered twice

in a Rails 3 application there are two models assinged to each other by belongs_to and has_one. On both sides there is :depended => :destroy configured for this association. now I had to add a :before_destroy callback in one of these models. the problem is now that this callback is triggered twice when an entity which includes this callback is destroyed. When I remove :depended => :destroy in the other model, it's triggered only once. So it seems this i causing the problem.

is there an elegant way to fix this ?

first non-reocurring letter of a string in ruby

I have a string "teststring" I want to find first non reoccurring character in ruby.

I tried this code

def first_non_repeat_character(teststring)
unique=[]
repeated=[]
for character in teststring:
if character in unique:
unique.remove(character)
repeated.append(character)
         else:
if not character in repeated:
unique.append(character)
if len(unique):
return unique[0]
else: 
return false`

How to Calculate sum of all the digits in text file

I am having text file t.txt,I want to calculate sum of all the digits in text file Example

    --- t.txt ---
The rahul  jumped in 2 the well. The water was cold at 1 degree Centigrade. There were 3 grip holes on the walls.  The well was 17 feet deep.
--- EOF --

sum 2+1+3+1+7 My ruby code to calculate sum is

ruby -e "File.read('t.txt').split.inject(0){|mem, obj| mem += obj.to_f}"

But i am not getting any answer??

mardi 29 septembre 2015

Omniauth Facebook not returning email and gender rails 4

I need to fetch name, email, image and gender from facebook. I am getting name and image, but email and gender is not fetched from facebook. I am struggling for past 2 days, can anyone help me out here.

User model:

def self.from_omniauth(auth)
  where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|       
    user.provider = auth.provider
    user.uid = auth.uid
    user.name = auth.info.name
    user.email = auth.info.email
    user.gender = auth.extra.raw_info.gender #if user.gender.blank?
    user.image = auth.info.image        
    user.save!
  end
end

Omniauth.rb

OmniAuth.config.logger = Rails.logger    
Rails.application.config.middleware.use OmniAuth::Builder do

if Rails.env.production?
  provider :facebook, '1186046461411581', 'ad1a6702b3e1c572e2b6c7c89b232c13'
elsif Rails.env.development?
  provider :facebook, '1186046461411581', 'ad1a6702b3e1c572e2b6c7c89b232c13', {:scope => 'publish_actions,email', :client_options => { :ssl => { :ca_file => "#{Rails.root}/config/ca-bundle.crt" }}}
else  
  provider :facebook, '1186046461411581', 'ad1a6702b3e1c572e2b6c7c89b232c13'
end  
end

If I use user.gender = auth.extra.raw.gender if user.gender.blank? it returns a null.

Even I have checked with my facebook privacy settings it is in public profiles only. Can anyone please help me out here

Embed form in email in Rails 3

I want to collect feedback through emails. For this I am thinking of embedding a feedback form in the email itself that the user can fill and submit. Upon submitting, the form will post data to my application where I can process the data.

Please suggest how this can be done or is there any other way I can achieve this.

Note: I also thought about embedding google form in my app but I can't figure out how this can be done. Also, my application is private, so, it can't be exposed to public.

Twitter reputation_system vote on no related model

I have a product model that belongs to shop

class Product < ActiveRecord::Base
  belongs_to :shop
has_reputation :votes, source: :user, aggregated_by: :sum

end

And i would like to vote on products with current_user

class User < ActiveRecord::Base

  has_one :shop,  :dependent => :destroy
  has_many :rs_evaluations, class_name: "ReputationSystem::Evaluation", as: :source

  has_reputation :votes, source: {reputation: :votes, of: :products}, aggregated_by: :sum

  def voted_for?(product)
    evaluations.where(target_type: product.class, target_id: product.id).present?
  end    
end

view

<% if current_user && !current_user.voted_for?(product) %>
  | <%= link_to "up", vote_product_path(product, type: "aumentar"), method: "post" %>
  | <%= link_to "down", vote_product_path(product, type: "diminuir"), method: "post" %>
<% end 

Someone have tried this before? thank's for any tip

Rails Route URL segment with + (plus) sign character in id is not parsed correctly

I have a TagsController class, with a route like the following (in routes.rb)

resources :tags

Now, when I go to

http://localhost:3000/tags/test

It works correctly.

However, when I go to

http://localhost:3000/tags/c++

Rails seems to be parsing the "c++" as "c ", so this results in a "404 Not Found"

Could anyone give me any instructions on how I could fix this?

Namespaced model in Rails generating NameError: uninitialized constant

I have a folder structure like this:

app/
  models/
    bar/
      foo.rb
      connection.rb
    foo.rb

connection.rb is an "abstract class" for connecting to another database, so:

class Bar::Connection < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "outsidedb_#{Rails.env}"
end

bar/foo.rb is for accessing the foos table from outsidedb, so:

class Bar::Foo < Bar::Connection
end

And foo.rb is for accessing the foos table from the app's db, so:

class Foo < ActiveRecord::Base
end

From the rails console if I do Foo.first or Bar::Foo.first things behave as a I would expect in that I get the first entry from the foos table of the app db and the external db, respectively.

However, if I try to access Foo from within bar/foo.rb I get the following:

class Bar::Foo < Bar::Connection
  def self.test
      Bar::Foo.first #=> works
      Foo.first      #=> NameError: uninitialized constant Bar::Foo::Foo
  end

  def self.other_test
    Foo.parent                    #=> Object
    Foo.superclass                #=> ActiveRecord::Base
    Object::Foo.first             #=> works
    ActiveRecord::Base::Foo.first #=> works, but with "warning: toplevel constant 
                                  #   Foo referenced by ActiveRecord::Base::Foo
  end
end

I can obviously get things working, but I'm looking for a sounder understanding of what's going on. I'm assuming I'm missing something between Ruby's constant/class evaluation and Rail's builtin auto-loading...

  1. What is .parent returning (not the 'parent' class)?
  2. Why do I get the error in .test, but I don't get it in the rails console?
  3. Why does Object::Foo seem to work? Is it the right thing to do?
  4. Why does ActiveRecord::Base::Foo work, but with a warning?
  5. There a more rails way to do what I've done without just renaming one of my foo.rb classes?

I'm on Rails '3.2.13' and Ruby 1.9.3-p194, just so you know!

Problems generating Rails route for weird URL

I have a URL that looks like this:

http://ift.tt/1O065Wu

I need to generate a rails route for this such that I can get namespace.001.587 out as the id and get it to route to the ImageViewer#show_image action, I also need to get 2down as the mode, and 1 as the page. Not being a clean RESTful URL, I'm finding this difficult to do in Rails. I'm only calling GET on this URL.

How would you generate this route?

Rails - four tables associations -

a rails newbie here, looking at doing some work with 4 tables and not totally sure how to structure the associations. Below topic involves real estate, probably helpful to keep that in mind.

I have four models: Property - a physical house Project - a large group of jobs happening at a house Job - a specific job at a house Worker - a person doing the work

The associations as I see them in my head are: - a Property can have many Projects, Jobs, and Workers - a single Project belongs to one Property, but can have many Jobs and (via Jobs) have many Workers - a single Job belongs to one Project and to one Property (via the Project), but can have many Workers - a single Worker can have one Job on one Projects on one Property

My two questions are:

1) What is the best way to think about the above set of relationships?

**2) How do I build the associations between my models? Can't get my head wrapped around how to do that.

Really appreciate any thoughts!

Combining truncate with Redcarpet markdown in Rails: Links don't work

I'm using Redcarpet for syntax highlighting in my Rails blog application.

In my posts/index.html.erb, I want to truncate the blog posts in order to preview the first few sentences (or paragraph). The user should be able to click on "read more" at the end of the truncated post to read the whole blog post. Unfortunately the "read more" link is not working with Redcarpet (when I don't use my markdown method (see below) the link is working fine). How can I fix that? Do I have to use other options in Redcarpet?

My markdown method in /helpers/application_helper.rb using Redcarpet:

def markdown(content)
  renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: true)
  options = {
    autolink: true,
    no_intra_emphasis: true,
    disable_indented_code_blocks: true,
    fenced_code_blocks: true,
    lax_html_blocks: true,
    strikethrough: true,
    superscript: true
  }

  Redcarpet::Markdown.new(renderer, options).render(content).html_safe
end

/views/posts/index.html.erb

<%=  markdown (truncate(post.content, 
                        length: 600, 
                        separator: ' ',
                        omission: '... ') {
                        link_to "read more", post 
               }) %>

By the way: I am looping through the @posts variable, so "post.content" gives me one post and "post" should give me the post's path.

The "read more" text is showing up but you cannot click on it. When I leave the "markdown" method out, the "read more"-link is working fine.

How can I create the link with my "markdown"-method?

encode_www_form converting space to + instead of %20

I am trying to create http parameters from a hash i have using Ruby on Rails, i have tried using URI.encode_www_form(params) , but this is not generating the parameters correctly.

Below is the hash i have

    params['Name'.to_sym] = 'Nia Kun'
    params['AddressLine1'.to_sym] = 'Address One'
    params['City'.to_sym] = 'City Name'

This method converts space to +, what i want is it to convert space with %20

i am getting "Name=Nia+Kun&AddressLine1=Address+One&City=City+Name" but i need ths spaces to be converted to %20

any help will be appricaited, Thanks.

Actions in InheritedResources::Base

Due to scaffolding I get

class CommentsController < InheritedResources::Base

In it not a single action shown. But when I add

resources :comments

in routes and url

http://localhost:3000/comments/13

it work properly but I can't understand from where this action inherit. I want to custom that action. Is it possible?

Implement single sign on functionality in rails 4

Currently I am trying to implement Single Sign On (SSO) in rails 4.

Consider the I have one main app demo.com and three sub-domain apps (basically each one is separate rails application) sub0.demo.com, sub1.demo.com, sub2.demo.com

Now I have to login all of the application through the demo.com (let consider I have same users on all of the applications)

For this I looked into the this post and tried to implement it.

So I have a following questions

  • Is it the good way for doing this?

  • As per the given link, I am trying to implement the given functionality for this I have did following steps

    1. As I am working on local, set the domain in /etc/hosts/ file

    127.0.0.1 demo.com

    127.0.0.1 sub0.demo.com

    127.0.0.1 sub1.demo.com

    1. Also made changes in the following files from the sub1.demo.com

session_store.rb

Rails.application.config.session_store :cookie_store, :key => '_tourlyapp_session', :domain => "demo.com"

But it is not working even though I have set the same key for all the application.

Is there any thing I am missing.

generating signature using base64_encode and hash_hmac in ruby on rails

I am con verting PHP code to Rails code and i am facing issues generating signature using base64_encode and hash_mac. The signature generated in php is 48 in length and while in Rails its varying in length.

How can i convert the below code to Rails

PHP Code:

return base64_encode(
    hash_hmac($hash, $data, $key, true)
);

Below is the Rails code i am using, but the singatures generated are of different length

Rails Code:

signature_val = Base64.encode64(OpenSSL::HMAC.digest('sha256', key, data))

Can anyone help me to convert the PHP code to Correct Rails code, so that i can generate the signature properly.

Thanks.

Paperclip Error: method_missing': undefined method `before_avatar_post_process'

Hello im just trying to run a simple migration to add header_image to my user model.

When i run the below migration:

rails generate paperclip user header_image

I receive this error:

/Users/joseph/.rvm/gems/ruby-2.1.2/gems/activerecord-4.2.0/lib/active_record/dynamic_matchers.rb:26:in `method_missing': undefined method `before_avatar_post_process' for User (call 'User.connection' to establish a connection):Class (NoMethodError)

Anyone know how to fix?

Paperclip is definitely installed.

Rails revoke token using doorkeeper gem

I am using Doorkeeper gem with device to authenticate my rest api application calls.

While deleting the user, I am just inactivating the user in back-end database so I wanna to revoke access token while I am deleting the account to prevent access by deleted user access token.

gender not fetch by omniauth facebook rails 4

I am using omniauth-facebook gem. I need to fetch gender and email from facebook, but it is not happening. Can anyone help me out here?

User Model

class User < ActiveRecord::Base
    attr_accessible :email, :name, :uid, :provider, :gender, :oauth_token, :oauth_expires_at    
    validates_presence_of :name, :uid
    validates_uniqueness_of :uid    

    def self.from_omniauth(auth)
      where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|       
        user.provider = auth.provider
        user.uid = auth.uid
        user.name = auth.info.name
        user.email = auth.info.email
        user.gender = auth.info.gender
        user.image = auth.info.image            
        user.save!
      end
    end
end

User Contoller

class UsersController < ApplicationController
respond_to :html, :json
def create
@user = User.from_omniauth(env["omniauth.auth"])
session[:user_id] = @user.id    
  redirect_to api_browsing_screen_url       
end  
end

omniauth.rb

OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
if Rails.env.production?
  provider :facebook, 'app_id', 'app_secret_key'
elsif Rails.env.development?
  provider :facebook, 'app_id', 'app_secret_key', {:scope => 'publish_actions,email', :client_options => { :ssl => { :ca_file => "#{Rails.root}/config/ca-bundle.crt" }}}
else  
  provider :facebook, 'app_id', 'app_secret_key'
end  
end

How to stubNokogiri in spec

How to stub Nokogiri in fetch method ofPromoDate in RSpec

 class PromoDate

      def self.fetch_data(request)
         page = Nokogiri::HTML(open("#{request.host}#{url}")) 
      end

    end

lundi 28 septembre 2015

Uninitialized Constant error (inside helper folder) after upgrading to Ruby 2.2.3 with RVM

I just upgraded from Ruby 1.9.3 to Ruby 2.2.3 using RVM and started getting the following output when I attempt to run rails server:

/Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/activesupport-3.2.22/lib/active_support/inflector/methods.rb:230:in `block in constantize': uninitialized constant Platform::AddressesHelper (NameError)
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/activesupport-3.2.22/lib/active_support/inflector/methods.rb:229:in `each'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/activesupport-3.2.22/lib/active_support/inflector/methods.rb:229:in `constantize'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/activesupport-3.2.22/lib/active_support/core_ext/string/inflections.rb:54:in `constantize'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/actionpack-3.2.22/lib/abstract_controller/helpers.rb:136:in `block in modules_for_helpers'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/actionpack-3.2.22/lib/abstract_controller/helpers.rb:131:in `map!'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/actionpack-3.2.22/lib/abstract_controller/helpers.rb:131:in `modules_for_helpers'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/actionpack-3.2.22/lib/action_controller/metal/helpers.rb:92:in `modules_for_helpers'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/actionpack-3.2.22/lib/abstract_controller/helpers.rb:95:in `helper'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/actionpack-3.2.22/lib/action_controller/railties/paths.rb:18:in `block (2 levels) in with'
from /Users/nathalia/workspace/my_app/app/controllers/application_controller.rb:2:in `<top (required)>'
from /Users/nathalia/workspace/my_app/app/controllers/admin_controller.rb:2:in `<top (required)>'
from /Users/nathalia/workspace/my_app/app/controllers/admin/aee_activities_controller.rb:2:in `<top (required)>'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/engine.rb:444:in `block (2 levels) in eager_load!'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/engine.rb:443:in `each'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/engine.rb:443:in `block in eager_load!'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/engine.rb:441:in `each'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/engine.rb:441:in `eager_load!'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/railtie/configurable.rb:30:in `method_missing'
from /Users/nathalia/workspace/my_app/config/initializers/paper_trail_ext.rb:86:in `<module:PaperTrail>'
from /Users/nathalia/workspace/my_app/config/initializers/paper_trail_ext.rb:15:in `<top (required)>'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/engine.rb:593:in `block (2 levels) in <class:Engine>'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/engine.rb:592:in `each'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/engine.rb:592:in `block in <class:Engine>'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/initializable.rb:30:in `instance_exec'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/initializable.rb:30:in `run'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/initializable.rb:55:in `block in run_initializers'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/initializable.rb:54:in `each'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/initializable.rb:54:in `run_initializers'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/application.rb:136:in `initialize!'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/railtie/configurable.rb:30:in `method_missing'
from /Users/nathalia/workspace/my_app/config/environment.rb:6:in `<top (required)>'
from /Users/nathalia/workspace/my_app/config.ru:3:in `block in <main>'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/rack-1.4.7/lib/rack/builder.rb:51:in `instance_eval'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/rack-1.4.7/lib/rack/builder.rb:51:in `initialize'
from /Users/nathalia/workspace/my_app/config.ru:in `new'
from /Users/nathalia/workspace/my_app/config.ru:in `<main>'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/rack-1.4.7/lib/rack/builder.rb:40:in `eval'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/rack-1.4.7/lib/rack/builder.rb:40:in `parse_file'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/rack-1.4.7/lib/rack/server.rb:200:in `app'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/commands/server.rb:46:in `app'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/rack-1.4.7/lib/rack/server.rb:304:in `wrapped_app'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/rack-1.4.7/lib/rack/server.rb:254:in `start'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/commands/server.rb:70:in `start'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/commands.rb:55:in `block in <top (required)>'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/commands.rb:50:in `tap'
from /Users/nathalia/.rvm/gems/ruby-2.2.3@my_app/gems/railties-3.2.22/lib/rails/commands.rb:50:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

This error seems to happen only within the folder helpers/platform. I thought this might be an issue with the module being under a namespace but I have other modules that are inside the helpers folder and work under a namespace that don't show the same error.

I am not sure if this is related to some configuration missing or maybe incompatibility with some of my gems. I don't know exactly how to proceed from this so maybe someone can help me to figure where should I be looking at? Do I need to provide more information?

Ruby 2.2.3 - Rails 3.2.22 - OS X Yosemite 10.10.4

How not get current_user

i'm breaking my head to get the user of this situation:

a conversation model:

has_many :conversation_participants, :dependent => :destroy
  has_many :users,
    :through => :conversation_participants
  has_many :messages, :dependent => :destroy
  has_one :display_message,
    :class_name => 'Message',
    :order => 'created_at DESC'

  def participants(options={})
    if options[:not].is_a? User
      users - [options[:not]]
    else
      users
    end
  end

and conversation_participants:

belongs_to :user
belongs_to :conversation
attr_accessible :user_id

on a conversation helper:

 def self_or_other
    @conversation.conversation_participants.find_by_user_id(:not => current_user)
  end

please, someone could clear me how to get the other user inside conversation_participants model?

Unable to test controller action in rspec

I am trying to test a controller action on a non-restful route.

config/routes.rb:

  match '/integration/:provider/callback' => "providers#manual_auth", as: :integration_callback

In my spec file:

spec/controllers/providers_controller_spec.rb:

describe ProvidersController do
  describe '#manual_auth' do
    it 'hits the manual_auth action' do
      get :manual_auth, use_route: :integration_callback
    end
  end
end

That gives me an error of:

Failures:

  1) ProvidersController#manual_auth hits the manual_auth action
     Failure/Error: get :manual_auth, use_route: :integration_callback
     ActionController::RoutingError:
       No route matches {:controller=>"providers", :action=>"manual_auth"}

However in app/controllers/providers_controller.rb I have

class ProvidersController < ApplicationController
  def manual_auth
    logger.info "Got into manual auth"
  end
end

I should mention I'm purposely avoiding a request spec here because I need to be able to access and set a session object(that lives in this #manual_auth action) which apparently can only be done in controller tests, not request specs.

how we can add the background color in full sheet using axlsx gem?

Here is my code and I want to add background color in full sheet not in a specific row or column.

xlsx_package = Axlsx::Package.new
   wb = xlsx_package.workbook
wb.add_worksheet(:name => "Basic Worksheet") do |sheet|
  sheet.add_row ["First Column", "Second", "Third"]
  sheet.add_row [1, 2, 3]
end

Any help will be appreciated! Thank you.

why the header contains "Content-Type": "Application/Json" will give me 500 error

when I initialize the http get request. If the header contains "content-type", "application/json", the server will report 500 error. If remove this header, the result is fine. Although the result is json.

Does it related to respond_to ?

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

I follow

http://ift.tt/MRKOSx

and done each and every thing according to this but when it gives me that error.

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

(anonymous function) @ products.js?body=1:36jQuery.Callbacks.fire @ application.js?body=1:3149jQuery.Callbacks.self.fireWith @ application.js?body=1:3261jQuery.extend.ready @ application.js?body=1:3473completed @ application.js?body=1:3504

My jquery code is

$(function() {

$("#textarea1").tokenInput("/products.json", {

crossDomain: false,

theme: "facebook"

});

}); Rails version is Rails 4.2.4 and ruby version is ruby 2.2.1

Ruby on Rails: http://localhost:3000 not working

Machines:

  • VM Machine (Ruby on Rails Server) - 192.168.1.37
  • Host Machine (Machine where the VM resides) - 192.168.1.38
  • Remote Machine (Dev Machine) - 192.168.1.36

Notes

  • VM Machine is running Cent OS (console only)
  • Host Machine is running Windows 7
  • VM emulator is Virtual Box
  • Remote Machine is Running on Windows 10

Pre-requisite

  • Added 192.168.1.37 as localhost in the Host Machine host file
  • start the rails service bundle exec rails s -p 3000

Problem

  • accessing site http://localhost:3000 NOT working
  • accessing site http://ift.tt/1Fv2Vc4 working

What Is Needed

  • Access the site via http://locahost:3000

Quirks

  • It works on remote machines running Linux (changed the host file to point to VM Machine as localhost)

how to get checkbox for subcategories in ruby

i want to display checkbox buttons to subcategory in ruby with its parent and child in ruby

like this

    `category
       checkbox subcategory
       checkbox subcategory
    category
       checkbox subcategory
       checkbox subcategory
    category
       checkbox subcategory
       checkbox subcategory`



    This is my code .
    ` <% Category.all.each do |c| %>
            <%= check_box_tag "category_ids[]", c.id, :id => "category_ids_#{c.id}" %>
            <%= c.name%>
            <% end %>`




please modify this . here i am getting every category and sub category with checked option. i want checkbox only to subcategories.

dimanche 27 septembre 2015

Update multiple rows using math to add to existing value

I am trying to update multiple rows. Some rows may have a value already. So if the value in that row was 2 and I wanted to update it with an additional 4 to make total of 6. How can I do that without querying each row for it's current value? Or must I do that?

I currently have something like thing like this.

item_match = Item.where("id IN (?)", item_match_ids).to_a
item_match.update_all(quantity: quantity)

How render a view of other controller and pass object?

How render a view of other controller and pass object?

For example: In a view controller Post i need render partial from controller Poll, i do the following:

.item_index  
  = f.fields_for :poll_items do |poll|
    = render :partial => 'polls/poll_item_fields', f: poll
  .links
    = link_to_add_association 'Add more', f, :poll_items, render_options: {class: 'links'}

and get error: **Showing /home/ubuntu/workspace/app/views/polls/_poll_item_fields.html.haml where line #3 raised:

undefined local variable or method `f' for #<#:0x0000000f56b170>**

Rails fragment caching - please help me understand

I have just started using caching in a production application to speed things up. I've read the primary Rails guide, various blogs, the source itself, etc. But my head is still not clear on one simple thing when it comes to fragment caching:

When you destroy the cache after updating the object, are you only updating the single object, or the class? I think just the single object.

Here's an example:

<% @jobs.each do |job| %>
   <% cache("jobs_index_table_environment_#{session[:merchant_id]}_job_#{job}") do %>
    stuff
   <% end %>
<% end %>

I use the code above in my jobs index page. Each row is rendered with some information the user wants, some CSS, clickable to view the individual job, etc.

I wrote this in my Job class (model)

after_save do
    Rails.cache.delete("jobs_index_table_environment_#{merchant_id}_job_#{self}")
  end

  after_destroy do
    Rails.cache.delete("jobs_index_table_environment_#{merchant_id}_job_#{self}")
   end

I want the individual job objects destroyed from the cache if they are updated or destroyed, and of course newly created jobs get their own cache key the first time they pop on the page.

I don't do the Russian doll thing with @jobs because this is my "god" object and is changing all the time. The cache would almost never be helpful as the collection probably morphs by the minute.

Is my understanding correct that in the above view, if I rendered, say, 25 jobs to the first page, I would get 25 objects in my cache with the cache key, and then if I only change the first, it's cached value would be destroyed and the next time the jobs page loads, it would be re-cached while the other 24 would just be pulled from the cache?

samedi 26 septembre 2015

Rails 4/Postgresql: better READ/WRITE query performance NULL vs STRING

I have a postgresql 9.4 column 'deal_status'.

On Deal create (model), I must decide for the attribute/column 'deal_status' between the 2 following options:

  • either do nothing and let the value null (or empty, not sure what happens in Rails when we don't say anything). When A deal is taken by a user, I'll change the value from NULL to a string ('deal_taken')

  • Or give inside the column a default value of 'deal_not_yet_taken'. When A deal is taken by a user, I'll change the value from a string ('deal_not_yet_taken') to another string ('deal_taken')

I have a very large amount of rows so I'm investigating more performance.

I have a method called 'show_deals_available' involving a postgresql query I'm trying to optimize for performance because it will occur a lot:

So what's the best/ fastest/most efficient for postgresql when it "executes" the query below:

1. option 1: Not giving any default value to deal_status attribute when a Deal is created (it will consequently have the value: NULL value); and query like this:

controller/deals_controller.rb

def show_deals_available
    @deal = Deal.friendly.find params[:id]
    @available_deal = Deal.where('deal_id = ? AND deal_status is NULL',
                             @deal.id).first  
    respond_to do |format|
      format.js 
    end
  end

2. option 2: Giving as default value a STRING when a deal is created : 'deal_not_yet_taken'; and make the following query:

controller/deals.rb

def show_deals_available
    @deal = Deal.friendly.find params[:id]
    @available_deal = Deal.where('deal_id = ? AND deal_status = ?',
                             @deal.id, "deal_not_yet_taken").first  
    respond_to do |format|
      format.js 
    end
  end

Plus maybe the answer is more complex as it seems. indeed the choice between the 2 options above, might be impacted also by the WRITE: when I'll have to change the value to 'deal_taken', is changing form string to another string compared to changing form NULL to a string ?

Note that I am using active record but the question remains true for postgresql (i might switch to raw postgresql in the future).

Rails 4/ UJS - ActionController::UnknownFormat - provide user with a way to directly open page with modal already opened

In my Ruby on Rails application, I am using Ajax through Rails' UJS (unobtrusive JavaScript).

It's perfectly working: when a user is on a Deal page, and when he then clicks on a certain textual link, the Ajax call is made and the modal with the distant content is loaded.

But I'd like to give a way to users to arrive directly on the page WITH the modal ALREADY OPENED, without him needing to load the Deal page and then click on the textual link. For example a user could receive en email and click on it and he would straight away arrive on Deal Page with the modal already opened.

But it's not working, when I take the route of the modal (see code below), and type in the browser http://ift.tt/1Wp6HIf , then it's giving the following error:

Completed 406 Not Acceptable in 29ms

ActionController::UnknownFormat - ActionController::UnknownFormat: actionpack (4.2.0) lib/action_controller/metal/mime_responds.rb:218:in respond_to' app/controllers/deals_controller.rb:70:inshow_opportunities'

Here are my files:

controller/deals_controller.rb

# used so that old urls created for deals redirects to the new ones created
# indeed with friendly_id, the url is taken from the title :/deals/title
# but if we edit the deal title to deal/title2, the old url was still    working
# we need to redirect the old url
# source - http://ift.tt/1Fm4JUL
before_filter :find_deal,
   :only => [  :showcase ]
before_filter :ensure_canonical_deal_path!,
  :only => [  :showcase ] 

def showcase    
    @deal = Deal.friendly.find(params[:id])   

    respond_to do |format|
      format.html # showcase.html.erb
      format.json { render json: @deal }
    end
end 

def show_opportunities
    @deal = Deal.friendly.find(params[:id])
    @opportunity = Opportunity.where('deal_id = ? AND deal_type = ?',
                             @deal.id, "high tech").first

    respond_to do |format|
      format.js
    end
end

protected

def find_deal
   @deal = Deal.friendly.find params[:id]
end
def ensure_canonical_deal_path!
   if request.path != deal_page_path(@deal)
        redirect_to deal_page_path(@deal, :format => params[:format]), :status => :moved_permanently
        return false
   end
end

app/views/deals/showcase.html.erb

<% if @deal.present? %>
   this is the beginning
   <%= render 'deals/deal_info_zone' %>
   this is the end
<% end %>

views/deals/_deal_info_zone.html.erb

<div id="zoneA">      
  <div style="color:red;padding-top: 150px;">
    <%= link_to "view infos of the latest Opportunity", deal_opportunities_modal_path, remote: true %>
  </div>
</div>

views/deals/deal_opportunities_modal.js.erb

Here is the modal trigger via Ajax: views/deals/opportunity_modal. Note here how I tried here to pass Deal but without success so that the line

$('body').append('<%= j render partial: "deals/deal_opportunities_modal" %>');
$('#myModal').modal('show');

/app/views/deals/_deal_opportunities_modal.html.erb

Here is the modal view/content now:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">

      <div class="modal-body"> 

          this the the latest opportunity: <%= @opportunity.name %> <br/>     

      </div>

    </div>
  </div>
</div>

routes.rb

match '/deals/:id', # this is the Deal page
    to:   'deals#showcase',
    via:  'get',
    as:   :deal_page

match '/deals/:id/opportunity_modal',
  to: 'deals#show_opportunities',
  via: 'get',
  as: :deal_opportunities_modal

How to achieve this, i.e. how to create a sort of route/URL that when used by a user, he arrives on Deal page with the modal 'show_opportunites' already open.

I heard about js-routes but it seems to be useful for other purposes (i.E use Rails routes inside javascript files).

Also is there a security issue if I enable the user to reach the page with the already-opened modal like that?

Cucumber Report Header Override using Ruby

I have generated cucumber report but I wanted to override Header which says "Cucumber Features" to use the environment variables defined which should look like "NAME1 NAME2 are the reports"

I am reading the arguments into an environment variable in ruby in env.rb file

appname1 = ENV['appname1'] appname2 = ENV['appname2']

cucumber appname1="NAME1" appname2="NAME2" -p features_01

I have looked into http://ift.tt/1Wp1XlH

How validate

I have a two model

Gallery

class Gallery < ActiveRecord::Base
    has_many :pictures, :dependent => :destroy

    accepts_nested_attributes_for :pictures, :allow_destroy => true

    attr_accessible :name, :description, :pictures_attributes

    validates_presence_of :pictures
end

Picture

    class Picture < ActiveRecord::Base
      belongs_to :gallery

      has_attached_file :image,
        :path => ":rails_root/public/images/:id/:filename",
        :url  => "/images/:id/:filename"
    end

And form

    <%= form_for @gallery, :html => { :class => 'form-horizontal', multipart: true } do |f| %>
    .........
     <div class="controls">
          <%= file_field_tag "images[]", type: :file, multiple: true %>
        </div>
    .........
    <% end %>

Controller

def create
    @gallery = Gallery.new(gallery_params)

    respond_to do |format|
      if @gallery.save

        if params[:images]         
          params[:images].each { |image|
            @gallery.pictures.create(image: image)
          }
        end

        format.html { redirect_to @gallery, notice: 'Gallery was successfully created.' }
        format.json { render json: @gallery, status: :created, location: @gallery }
      else
        format.html { render action: "new" }
        format.json { render json: @gallery.errors, status: :unprocessable_entity }
      end
    end
  end

If I want to validate has_many pictures image blank?, I got every time a error that Pictures is blank, even I selected images.

How I validate has_many association with multiple image field?

vendredi 25 septembre 2015

Adding new page into Rails 4 Application

I have new Rails project, in the project I have a controller, view and model named as Customer. Now, what I need is that beside the CRUD actions I need to add two new pages like:

1. http://ift.tt/1KIvbVv

2. http://ift.tt/1FnP07H

And I want to insert code in these files. How do I achieve this I mean creating new sale and lease links?

How is this sent to the Show action

I am new to ruby on rails and i want to understand how this piece of code redirect to the show action thanks :

  def create
  @article = Article.new(params[:article])
 
  @article.save
  redirect_to @article
end

Rails j render partial with locals

I am attempting to render a partial using Ajax, where I send the relevant Javascript object to the partial using locals. Unfortunately, I'm having trouble sending the object and I keep getting the error "undefined local variable".

controller:

class TransportationController < ApplicationController
    respond_to :html, :js, :json 

create.js.erb

function getRates(){
    $.ajax( {
      ...
      (code cut out that's irrelevant to question, but this request succeeds)
      ...

      success: function( json ) {
        json.prices.forEach(function(price){
                $("#my_list").append("<%= j render :partial => 'my_item', :locals => {price: price} %>");
            });
            ....    
};

_my_item.html.erb:

    ....
        <h1><%= price.display_name %></h1>
    ....

Error: (NameError - undefined local variable or method `price')

Any help to sort this out would be greatly appreciated! I thought I was doing it correctly

Why does render and redirect not stop execution in a Rails app?

I have a use case question. In Rails 4.1 if you run a controller method and have redirect_to or render at some point in your method you are still allowed to continue execution at that point. Sometimes this results in a AbstractController::DoubleRenderError if you dont handle your control flow properly. Why is this allowed in Rails? It seems like a funny use case to redirect and not stop execution, when would this be appropriate?

The full error message is listed below:

  AbstractController::DoubleRenderError:
       Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".

Disable javascript UJS caching (Rails 4)

I am using Rails 4 and unobstrusive javascript(UJS) to make a ajax call:

I'd like to disable the caching so that if somebody clicks the same link again and that the content in databse has changed, a new content will load inside the modal.

Some people do:

$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});

How to write this with Rails?

<%= link_to "view", show_opportunities_path, remote: true, cache: false %> does not work.

Rails 4/Ajax ujs/Turbolinks - Ajax activated bootstrap Modal does not change content despite value in database changing

I have a Ruby on Rails app (plus Bootstrap on frontend).

I'm using ajax to load a modal.

Here is what I want to do:

  1. On a Deal page, the user clicks on a link called "view opportunities'

  2. A modal appears and inside the text you can see: "the latest opportunity is Star Wars 3 DVD" (hat's an example) (see code below). so it retrieved data from the table/model Opportunity to show it to the user. => this works perfectly thanks to ajax and all

  3. Now here is the bug, i.e my problem: When the user closes the modal, and then REclick (;.e. he clicks another time) on the same link "view opportunities", the modal appears but instead of going back to the database/table 'Opportunity' to check what is the latest Opportunity, it just displays again the same content ("Star Wars 3 DVD") where as it should show something else(I manually changed inside the database the latest opportunity he should show).

My first thought was to think it might be due to Turbolinks which can cache heaps of stuff behind the scene BUT I'm not sure now. Indeed, I tried to put data-no-turbolink on parent container, still had the same problem. then added data-no-turbolink on , still the same problem. I even tried to put inside "Turbolinks.disableRequestCaching(); .

There are many people who had trouble with turbolinks and bootstrap modals (here for example) and I might have problem because my javascript is not sent into the head but the ? I'm confused...

If I could describe with rookie words what's happening, it's that something is preventing me to click on the link and send a new ajax/xhr request to the database and instead is sending the same content to the view.

Can anyone help?

Here are my files:

controller/deals_controller.rb

# used so that old urls created for deals redirects to the new ones created
# indeed with friendly_id, the url is taken from the title :/deals/title
# but if we edit the deal title to deal/title2, the old url was still    working
# we need to redirect the old url
# source - http://ift.tt/1Fm4JUL
before_filter :find_deal,
   :only => [  :showcase ]
before_filter :ensure_canonical_deal_path!,
  :only => [  :showcase ] 

def showcase    
    @deal = Deal.friendly.find(params[:id])   

    respond_to do |format|
      format.html # showcase.html.erb
      format.json { render json: @deal }
    end
end 

def show_opportunities
    @deal = Deal.friendly.find(params[:id])
    @opportunity = Opportunity.where('deal_id = ? AND deal_type = ?',
                             @deal.id, "high tech").first

    respond_to do |format|
      format.js
    end
end

protected

def find_deal
   @deal = Deal.friendly.find params[:id]
end
def ensure_canonical_deal_path!
   if request.path != deal_page_path(@deal)
        redirect_to deal_page_path(@deal, :format => params[:format]), :status => :moved_permanently
        return false
   end
end

app/views/deals/showcase.html.erb

<% if @deal.present? %>
   this is the beginning
   <%= render 'deals/deal_info_zone' %>
   this is the end
<% end %>

views/deals/_deal_info_zone.html.erb

<div id="zoneA">      
  <div style="color:red;padding-top: 150px;">
    <%= link_to "view infos of the latest Opportunity", deal_opportunities_modal_path, remote: true %>
  </div>
</div>

views/deals/deal_opportunities_modal.js.erb

Here is the modal trigger via ajax: views/deals/opportunity_modal. Note here how I tried here to pass Deal but without success so that the line

$('body').append('<%= j render partial: "deals/deal_opportunities_modal" %>');
$('#myModal').modal('show');

/app/views/deals/_deal_opportunities_modal.html.erb

Here is the modal view/content now:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">

      <div class="modal-body"> 

          this the the latest opportunity: <%= @opportunity.name %> <br/>     

      </div>

    </div>
  </div>
</div>

routes.rb

match '/deals/:id', # this is the Deal page
    to:   'deals#showcase',
    via:  'get',
    as:   :deal_page

match '/deals/:id/opportunity_modal',
  to: 'deals#show_opportunities',
  via: 'get',
  as: :deal_opportunities_modal

gemfile has included: gem 'jquery-turbolinks'

assets/javascript/application.js

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require jquery.cookie
//= require twitter/bootstrap
//= require paloma
//= require html5shiv-printshiv
//= require turbolinks
//= require_directory .

Tell me if some other files would useful to find the answer

Rails 4/ ajax - NoMethodError - undefined method `id' for nil:NilClass - Passing variable to js modal

I have a pretty simple Ruby On Rails app with bootstrap 3 for the front end: I have Deals, and each Deal has_many Opportunities.

On each Deal page (url of deal page is for example myapp.com/id=1), I want to have a textual link that says "view deal's opportunities" and when clicked, it trigger when clicked the appearance of content inside a Bootstrap modal.

I'm getting all mixed up because on this Deal Page, I use Deal's controller action called "showcase". BUT to generate the modal via ajax,as you see below, I use another action called "show_opportunities" and inside it, the app seems not to know @deal (because@deal is defined in a different Deal's action). I think that where the problem comes form but I am not totally sure.

Here is the error I am getting and my code:

Processing by DealsController#show_opportunities as JS
Completed 500 Internal Server Error in 3ms

NoMethodError - undefined method `id' for nil:NilClass:
  app/controllers/deals_controller.rb:72:in `show_opportunities'

This line where 72 with the error is "@deal.id, "high tech").first" (see below)

controller/deals_controller.rb

def showcase    
    deals = Deal.friendly.find(params[:id])   

    respond_to do |format|
      format.html # showcase.html.erb
      format.json { render json: @deal }
    end
end 

def show_opportunities
    @opportunity = Opportunity.where('deal_id = ? AND deal_type = ?',
                             @deal.id, "high tech").first

    respond_to do |format|
      format.js
    end
end

app/views/deals/showcase.html.erb

this is the beginning
<%= render 'deals/deal_info_zone' %>
this is the end

views/deals/_deal_info_zone.html.erb

<div id="zoneA">      
  <div style="color:red;padding-top: 150px;">
    <%= link_to "view infos of Opportunities", deal_opportunities_modal_path, remote: true %>
  </div>
</div>

views/deals/deal_opportunities_modal.js.erb

Here is the modal trigger via ajax: views/deals/opportunity_modal. Note here how I tried here to pass Deal but without success so that the line

$('body').append('<%= j render partial: "deals/deal_opportunities_modal", locals:{deal: @deal} %>'); 
$('#myModal').modal('show');

/app/views/deals/_deal_opportunities_modal.html.erb

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">

      <div class="modal-body"> 

          <%= @opportunity.name %> <br/>     

      </div>

    </div>
  </div>
</div>

routes.rb

match '/deals/:id', # this is the Deal page
    to:   'deals#showcase',
    via:  'get',
    as:   :deal_page

match '/opportunity_modal',
    to:   'deals#show_opportunities',
    via:  'get',
    as:   :deal_opportunities_modal

How to make this work ?

EDIT with Pavan feedback

Pavan suggested putting @deal inside #show_opportunities

Si I tried to change controller/deals_controller.rb:

def showcase    
    deals = Deal.friendly.find(params[:id])   

    respond_to do |format|
      format.html # showcase.html.erb
      format.json { render json: @deal }
    end
end 

def show_opportunities
    @deal = Deal.friendly.find(params[:id])
    @opportunity = Opportunity.where('deal_id = ? AND deal_type = ?',
                             @deal.id, "high tech").first

    respond_to do |format|
      format.js
    end
end

but I get the error:

Completed 404 Not Found in 3ms

ActiveRecord::RecordNotFound - Couldn't find Deal without an ID:
 activerecord (4.2.0) lib/active_record/relation/finder_methods.rb:433:in `find_with_ids'
  activerecord (4.2.0) lib/active_record/relation/finder_methods.rb:71:in `find'
  friendly_id (5.1.0) lib/friendly_id/finder_methods.rb:20:in `find'
  app/controllers/deals_controller.rb:70:in `winalert'

I thought I'd just remove the "friendly" (comes from friendly_id gem) from the code above but am still getting an error:

Started GET "/opportunity_modal" for 127.0.0.1 at 2015-09-25 15:15:40 +0200
Processing by DealsController#show_opportunities as JS
  Deal Load (0.5ms)  SELECT  "deals".* FROM "deals" WHERE "deals"."id" = $1 LIMIT 1  [["id", nil]]
Completed 404 Not Found in 5ms

ActiveRecord::RecordNotFound - Couldn't find Deal with 'id'=:
activerecord (4.2.0) lib/active_record/core.rb:154:in `find'

how to create web service Api in rails 4?

can anyone help me how to create a web service API in rails 4. I know how create web service API in ruby 1.8.7 and rails 2.3.5 with action web service gem. When I am trying to use http://ift.tt/1Mts3iY gem in rails 4, I am getting deprecated errors.I want to upgrade my web service app. Please help me.

Thanks in advance.

jeudi 24 septembre 2015

Rails - Uploading large files directly to S3 with Jquery File Upload (hosted on Heroku )

I'm using Heroku, which means I have to upload multiple large files to S3 directly.. I'm using Rails 3.2.11, and Ruby 1.9.3. I do not wish to use carrierwave or paperclip gems, or really change much at this point - I just need to get this what I have working.

Before trying to move to S3, if I ran my app locally, I could upload multiple large files to the local file system. When I ran it on Heroku, small files upload but large ones failed. Hence the switch to S3..

I tried several tweaks, and also this link below, but it's just too much of a change to what I have that already working with the local server's file system (and Heroku as well, but Heroku just can't handle large files ..)

Tried: http://ift.tt/1rlOGxv

I've tried some of the other examples here on Stack Overflow but they are too much of a change for what works locally, and well, I don't grasp everything they are doing.

Now, what happens when I do try to upload images?

It's as if the file upload works - the preview images are successfully created, but nothing is ever uploaded to Amazon s3, and I don't receive any kind of error messages (like s3 authentication failure or anything.. nothing)

What do I need to change in order to get the files over to my s3 storage, and what can I write out to console to detect problems, if any, connecting to my s3?

My form:

        <%= form_for @status  do |f| %>

        {A FEW HTML FIELDS USED FOR A DESCRIPTION OF THE FILES - NOT IMPORTANT FOR THE QUESTION}

        File:<input id="fileupload"  multiple="multiple"  name="image" 
            type="file"  data-form-data = <%= @s3_direct_post.fields%> 
            data-url= <%= @s3_direct_post.url %> 
            data-host =<%=URI.parse(@s3_direct_post.url).host%> >   
        <%= link_to 'submit', "#", :id=>'submit' , :remote=>true%>

        <% end %>

My jquery is:

....
  $('#fileupload').fileupload({
      formData: {
                 batch: createUUID(),
                  authenticity_token:$('meta[name="csrf-token"]').attr('content')
                    },
      dataType: 'json',
      acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
              maxFileSize: 5000000, // 5 MB
              previewMaxWidth: 400,
              previewMaxHeight: 400,
              previewCrop: true,
      add: function (e, data) {

      tmpImg.src = URL.createObjectURL(data.files[0]) ; // create image preview 
      $('#'+ fn + '_inner' ).append(tmpImg);

    ...

My controller:

def index
#it's in the index just to simplify getting it working 

 @s3_direct_post = S3_BUCKET.presigned_post(key: "uploads/#{SecureRandom.uuid}/${filename}", success_action_status: '201', acl: 'public-read')

end

The element on the form is

        <input id="fileupload" multiple="multiple" name="image" 
    data-form-data="{&quot;key&quot;=>&quot;uploads/34a64607-8d1b-4704-806b-159ecc47745e/${filename}&quot;," &quot;success_action_status&quot;="
    >&quot;201&quot;," &quot;acl&quot;=">&quot;public-read&quot;," &quot;policy&quot;=">&quot;[encryped stuff - no need to post]&quot;,"
     &quot;x-amz-credential&quot;=">&quot;
[AWS access key]/[some number]/us-east-1/s3/aws4_request&quot;
," &quot;x-amz-algorithm&quot;=">&quot;AWS4-HMAC-SHA256&quot;
," &quot;x-amz-date&quot;=">&quot;20150924T234656Z&quot;
," &quot;x-amz-signature&quot;=">&quot;[some encrypted stuff]&quot;}"
data-url="http://ift.tt/1gSMJ8C" data-host="nunyabizness.s3.amazonaws.com" type="file">

Help!

Rails 4 - Display data inside a bootstrap modal via ajax

I have a pretty simple Ruby On Rails app with bootstrap 3 for the front end: I have Deals, and each Deal has_many Opportunities.

On each Deal page (url of deal 1 is like myapp.com/id=1), I want to have a textual link that says "view deal's opportunities" and that must trigger when clicked the appearance of content inside a Bootstrap modal.

Very basic but for specific reasons, I wish to load the content of the modal via Ajax.(the content is not visible when users load the Deal page but only when they click on the link 'view deal's opportunities'

I found many resources online for Rails4/ajax/Forms and other stuff with Ajax but not a simple "display content/text" inside a modal via Ajax. Should be easy but I'm stuck.

controller/deals_controller.rb

def showcase    
    deals = Deal.friendly.find(params[:id])   

    respond_to do |format|
      format.html # showcase.html.erb
      format.json { render json: @deal }
    end
end 

def show_opportunities

    @opportunities = Opportunity.where('deal_id = ? AND deal_type = ?',
                             @deal.id, "high tech").first

    respond_to do |format|
      format.js
    end

  end

app/views/deals/showcase.html.erb

this is the beginning
<%= render 'deals/deal_info_zone' =>
this is the end

views/deals/_deal_info_zone.html.erb

<div id="zoneA">  

  <div style="color:red;padding-top: 150px;">
    <%= link_to "view infos of Opportunities", deal_opportunities_modal_path, remote: true %>
  </div>
</div>

Here is the modal I'd like to trigger via ajax: views/deals/opportunity_modal

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">

      <div class="modal-body"> 

          <%= @opportunity.name %> <br/>     

      </div>

    </div>
  </div>
</div>

routes.rb

match '/deals/:id', # this is the Deal page
    to:   'deals#showcase',
    via:  'get',
    as:   :deal_page

match '/opportunity_modal',
    to:   'deals#show_opportunities',
    via:  'get',
    as:   :deal_opportunities_modal

I'm a rookie in RoR and have never used ajax, ujs maybe... I feel it's missing things like javascript code and xhr request...

The current situation is this one: when I go on a Deal page (for ex page /deal id=1) the textual link "view infos of Opportunities". and the browser points to http://localhost:3000/opportunity_modal but it does not trigger anything when I click on it. Nothing happens. Nothing gets displayed btw on firebug console.

Can anyone help? thanks

How to pass locales in simple_fields_for partials?

I have the following code in My View:

<%= simple_form_for @user do |f| %>
  <%= f.input :email %>
  <%= simple_fields_for :profile do |p| %>
   <%= render 'profile_fields', f => p %>
 <% end %>
 <%= f.submit %>

So I was trying to pass locales for 'profile_fields' partial the following way and am trying access that locale in partial, it was throwing an error like "Undefined method type".

<%= simple_fields_for :profile do |p| %>
 <%= render 'profile_fields', f => p, :type => "Test" %>
<% end %>

Can anyone help me?

RubyMine inline refactoring?

Here is some long-form code:

  c.jobs.each do |j|
    j.products.each do |p|
      p.destroy
    end
    j.payments.each do |p|
      p.destroy
    end
    j.destroy
  end

RubyMine has an inline refactoring tool, but it's disabled when I try to refactor any part of this.

I would expect to be able to click on the do by products and inline refactor to:

j.products.each { |p| p.destroy }

In a single keystroke.

What am I doing wrong?

mailer with gmail gives Net::SMTPAuthenticationError: with 2-factor auth disabled

I am getting a Net::SMTPAuthenticationError both on my development (local) env as well as when I host on Heroku, when I try to send mails from my rails application.

This started after sending the first couple of email (2 mails to be specific).

All research so far made me think that this should could be due to having a 2-factor auth enabled on the gmail account, but when I checked the account, 2-factor autt was not enabled.

screenshot of the 2-factor auth setting on my account

below is my smtp setting both in config/development.rb and config/production.rb:

  config.action_mailer.delivery_method = :smtp
  # SMTP settings for gmail
  config.action_mailer.smtp_settings = {
      :address              => "smtp.gmail.com",
      :port                 => 587,
      :user_name            => Rails.configuration.gmail_address,
      :password             => Rails.configuration.gmail_password,
      :authentication       => "plain",
      :enable_starttls_auto => true
  }

My mailer is set up as follow:

class StackoMailer < ActionMailer::Base

    def success_mail
      @my_email = Rails.configuration.gmail_address
      mail(
        from: 'notifications@StackoProbe.com',
        to: @my_email,
        subject: 'Fuck Yeah! Visited successfully...'
      )
    end
end

On calling PushWatir::StackoMailer.success_mail.deliver_now!, I get the following error:

2.2.1 :001 > PushWatir::StackoMailer.success_mail.deliver_now!
Net::SMTPAuthenticationError: 534-5.7.14 <http://ift.tt/1NOZYnQ

    from /Users/andela/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/net/smtp.rb:976:in `check_auth_response'
    from /Users/andela/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/net/smtp.rb:740:in `auth_plain'
    from /Users/andela/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/net/smtp.rb:732:in `authenticate'
    from /Users/andela/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/net/smtp.rb:567:in `do_start'
    from /Users/andela/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/net/smtp.rb:520:in `start'
    from /Users/andela/.rvm/gems/ruby-2.2.1/gems/mail-2.6.3/lib/mail/network/delivery_methods/smtp.rb:112:in `deliver!'
    from /Users/andela/.rvm/gems/ruby-2.2.1/gems/mail-2.6.3/lib/mail/message.rb:252:in `deliver!'
    from /Users/andela/.rvm/gems/ruby-2.2.1/gems/actionmailer-4.2.4/lib/action_mailer/message_delivery.rb:77:in `deliver_now!'
    from (irb):1
    from /Users/andela/.rvm/gems/ruby-2.2.1/gems/railties-4.2.4/lib/rails/commands/console.rb:110:in `start'
    from /Users/andela/.rvm/gems/ruby-2.2.1/gems/railties-4.2.4/lib/rails/commands/console.rb:9:in `start'
    from /Users/andela/.rvm/gems/ruby-2.2.1/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:68:in `console'
    from /Users/andela/.rvm/gems/ruby-2.2.1/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /Users/andela/.rvm/gems/ruby-2.2.1/gems/railties-4.2.4/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:8:in `require'
    from bin/rails:8:in `<main>'
2.2.1 :002 > 

What could be causing this?

How can I make this work? Big thanks for responses

Rails table associations has_many through

I'm new in Rails and am working on a problem. I have two tables:

Shoes and Socks

A Shoe can have many Socks, but only one active Sock. Other Socks are inactive. All Socks are also unique with unique patterns. I think I can do this three ways

1) Using an additional column in table socks to represent the active sock

class Shoe < ActiveRecord::Base
  has_many :socks
end

class Socks < ActiveRecord::Base
  belongs_to :shoe
end

class CreateGettingDressed < ActiveRecord::Migration
  def change
    create_table :shoes do |t|
      t.string :size
      t.timestamps null: false
    end

    create_table :socks do |t|
      t.belongs_to :shoe, index:true
      t.string :pattern
      t.boolean :active
      t.timestamps null: false
    end
  end
end

This seems fairly simple, but cumbersome. I would search socks with shoe_id, and pull out the active_sock and return it's pattern. I think I would index [active_sock, shoe_id] in an array to speed it up.

2) Using an additional table to archive inactive socks

class Shoe < ActiveRecord::Base
  has_many :socks
  has_many :inactive_socks
end

class Socks < ActiveRecord::Base
  belongs_to :Shoe
end

class Inactive_socks < ActiveRecord::Base
  belongs_to :Shoe
end

class CreateGettingDressed < ActiveRecord::Migration
  def change
    create_table :shoes do |t|
      t.string :name
      t.timestamps null: false
    end

    create_table :socks do |t|
      t.belongs_to :shoe, index:true
      t.string :pattern
      t.timestamps null: false
    end


    create_table :inactive_socks do |t|
      t.belongs_to :shoe, index:true
      t.string :pattern
      t.timestamps null: false
    end
  end
end

This seems cumbersome as well, but when you are just dealing with active socks easy to use and fast. But when buying a new sock, I have to check the pattern with both tables.

3) Using a has_many :through relationship

class Shoe < ActiveRecord::Base
  has_many :active_socks
  has_many :socks, through: active_socks 
end

class Active_Socks < ActiveRecord::Base
  belongs_to :Shoe
  belongs_to :Sock
end

class Socks < ActiveRecord::Base
  has_many :active_socks
  has_many :shoes, through: active_socks
end

class CreateGettingDressed < ActiveRecord::Migration
  def change
    create_table :shoes do |t|
      t.string :name
      t.timestamps null: false
    end

    create_table :socks do |t|
      t.string :pattern
      t.timestamps null: false
   end

    create_table :active_socks do |t|
      t.belongs_to :shoe, index: true
      t.belongs_to :sock, index: true
      t.string :pattern
      t.boolean :active
      t.timestamps null: false
    end
  end
end

This seems like option 2, but I feel like I'm using Rails tools to make it less cumbersome. When I'm searching for patterns I'm just checking the socks table, when I'm searching for the one active_sock I'm just searching active_socks table.

I've read up on similar posts, and it seems options 1 and 2 are commonly used in closed_accounts, banning users, banning posts, archiving etc. Situations where you need to differentiate data that is only slightly different. The choice there seems to be look at what you need and choose the option 1 or 2 that best fits you.

My understanding for has_many through situations seems to be when you have a relationship and you need extra meta data you can use it. I think that fits this situation.

Did I set up option 1 correctly and am I right that indexing the array of [shoe_id and active] will give me a faster search? Is option 3 an appropriate use of has_many through? Would my explanation of option 3 work?

No such file to load -- devise/confirmations_controller resque error in rails using chef

Im trying to integrate resque in my application using resque cookbook(chef).I start the resque workers by monit like start program = "/usr/bin/sudo /engineyard/bin/resque <%= @app_name %> start <%= @rails_env %> resque_<%= num %>.conf" with timeout 60 seconds. But in production,it show this error message No such file to load -- devise/confirmations_controller I know rake environment QUEUE=* resque:work will do the work. But how do i do it in monit?

mercredi 23 septembre 2015

Error message when running Rake command in Rails app

I'm trying to create posts in my Rails app by pulling data from a CSV file.

When I try to run a Rake command, I get the error message below. What's wrong with this code?

SEED.RAKE FILE

require 'csv'

namespace :csv do

  desc "Import CSV Data for Michelin Star Restaurants"
  task :post => :environment do

    csv_file_path = 'db/data.csv'

    CSV.foreach(csv_file_path) do |row|
        Post.create({
          :name => row[1],
          :address => row[2],
          :city => row[3],
          :michelin_status => row[4],
          :website => row[5],
          :phone => row[6],
          :longitude => row[7],
          :latitude => row[8],
          :inthenews => row[9],
          :google_reviews => row[10],
        })
      end
    end
  end

ERROR MESSAGE FROM CONSOLE

Faisals-Air:dinner fkhalid2008$ rake csv:post
rake aborted!
ArgumentError: invalid byte sequence in UTF-8
/Users/fkhalid2008/dinner/lib/tasks/seed.rake:11:in `block (2 levels) in <top (required)>'
/Users/fkhalid2008/.rvm/gems/ruby-2.2.0/bin/ruby_executable_hooks:15:in `eval'
/Users/fkhalid2008/.rvm/gems/ruby-2.2.0/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => csv:post
(See full trace by running task with --trace)

DB MIGRATE FILE

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :name
      t.string :inthenews
      t.string :michelin_status
      t.string :google_reviews
      t.string :address
      t.string :city
      t.string :website
      t.integer :phone
      t.integer :longitude
      t.integer :latitude

      t.timestamps null: false
    end
  end
end

LinkedIn API session issue

Hi StackOverflow community

Our web app is built around Ruby on Rails 3. We use the linkedin rubygem to integrate the LinkedIn API.

We have successful Linkedin sign-in and registrations, but at rare cases (occurring twice or thrice a year so far), a user logins/registers via LinkedIn but a totally different and unconnected user shows up. (UserA enters LinkedIn credentials for the permissions, but some LinkedIn UserB gets returned). We don't get why this happens at all.

Here is the code snippet for the OAuth url:

 client = LinkedIn::Client.new('app_token', 'app_secret', @@config)
 request_token = client.request_token(:oauth_callback => "http://#{request.host}:#{request.port}/auth/oauth_account")
 session[:rtoken] = request_token.token
 session[:rsecret] = request_token.secret
 session[:provider_user] = "linkedin"
 redirect_to request_token.authorize_url

The bug highly makes it insecure for users. Could someone help?

Mina EC2 deployment saving cache issue

After deploy on a ec2 instance with mina i check the production log file and i faced with:

Warning. Error encountered while saving cache /home/ubuntu/bacana/tmp/build-1442877527942/tmp/cache/sass/d78f1e46c5027b7748b2f94fb1049a601a88a/jquery.dataTables.scssc: can't dump anonymous class #Class:0x007f1a650e

please, someone would explain what this mean?

obs: i'm using asset_sync!

Ruby on Rails Custom Rails Resource Routing Error Pages

I would like to route all broken site links for a rails resource to a particular custom error page and all other broken links to another custom error page. For example:

/locations/wrong-location - Invalid location error page

/products/wrong-product - Invalid product error page

Does anyone know how to do this in Rails 3.2?

Msfvenom not working "uninitialized constant ApplicationController"

It gives this response on Windows.

DL is deprecated, please use Fiddle D:/metasploit/apps/pro/vendor/bundle/ruby/2.1.0/gems/wicked-0.5.0/app/controllers/wicked/wizard_controller.rb:5:in <top (required)>': uninitialized constant ApplicationController (NameError) from D:/metasploit/apps/pro/vendor/bundle/ruby/2.1.0/gems/railties-4.0.13/lib/rails/engine.rb:465:in block (2 levels) in eager_load!' from D:/metasploit/apps/pro/vendor/bundle/ruby/2.1.0/gems/railties-4.0.13/lib/rails/engine.rb:464:in each' from D:/metasploit/apps/pro/vendor/bundle/ruby/2.1.0/gems/railties-4.0.13/lib/rails/engine.rb:464:in block in eager_load!' from D:/metasploit/apps/pro/vendor/bundle/ruby/2.1.0/gems/railties-4.0.13/lib/rails/engine.rb:462:in each' from D:/metasploit/apps/pro/vendor/bundle/ruby/2.1.0/gems/railties-4.0.13/lib/rails/engine.rb:462:in eager_load!' from D:in eager_load!' from D:/metasploit/apps/pro/vendor/bundle/ruby/2.1.0/gems/railties-4.0.13/lib/rails/application/finisher.rb:56:in each' from D:/metasploit/apps/pro/vendor/bundle/ruby/2.1.0/gems/railties-4.0.13/lib/rails/application/finisher.rb:56:in block in <module:Finisher>' from D:/metasploit/apps/pro/vendor/bundle/ruby/2.1.0/gems/railties-4.0.13/lib/rails/initializable.rb:30:in instance_exec' from D:/metasploit/apps/pro/vendor/bundle/ruby/2.1.0/gems/railties-4.0.13/lib/rails/initializable.rb:30:in run' from D:/metasploit/apps/pro/vendor/bundle/ruby/2.1.0/gems/railties-4.0.13/lib/rails/initializable.rb:55:in block in run_initializers' from D:/metasploit/ruby/lib/ruby/2.1.0/tsort.rb:226:in block in tsort_each' from D:/metasploit/ruby/lib/ruby/2.1.0/tsort.rb:348:inblock (2 levels) in each_strongly_connected_component' from D:/metasploit/ruby/lib/ruby/2.1.0/tsort.rb:427:in each_strongly_connected_component_from' from D:/metasploit/ruby/lib/ruby/2.1.0/tsort.rb:347:inblock in each_strongly_connected_component' from D:/metasploit/ruby/lib/ruby/2.1.0/tsort.rb:345:in each' from D:/metasploit/ruby/lib/ruby/2.1.0/tsort.rb:345:incall' from D:/metasploit/ruby/lib/ruby/2.1.0/tsort.rb:345:in each_strongly_connected_component' from D:/metasploit/ruby/lib/ruby/2.1.0/tsort.rb:224:intsort_each' from D:/metasploit/ruby/lib/ruby/2.1.0/tsort.rb:205:in tsort_each' from D:/metasploit/apps/pro/vendor/bundle/ruby/2.1.0/gems/railties-4.0.13/lib/rails/initializable.rb:54:in run_initializers' from D:/metasploit/apps/pro/vendor/bundle/ruby/2.1.0/gems/railties-4.0.13/lib/rails/application.rb:215:in initialize!' from D:/metasploit/apps/pro/vendor/bundle/ruby/2.1.0/gems/railties-4.0.13/lib/rails/railtie/configurable.rb:30:in method_missing' from D:/metasploit/apps/pro/msf3/config/environment.rb:5:in <top (required)>' from D:/metasploit/apps/pro/msf3/lib/msfenv.rb:18:inrequire' from D:/metasploit/apps/pro/msf3/lib/msfenv.rb:18:in <top (required)>' from D:/metasploit/ruby/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:54:in require' from D:/metasploit/ruby/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:54:in require' from msfvenom:10:in'

Error when adding an export to CSV button to Ruby On Rails project

Im getting the following error when adding a export to CSV button on my Hotel Model.

Missing template hotels/index, application/index with {:locale=>[:en], :formats=>[:csv], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml, :jbuilder]}. Searched in:
  * "/Users/kallan1/Desktop/GSW-CRM/app/views"
  * "/Users/kallan1/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/devise-3.4.1/app/views"

Thanks in advance and let me know if you need any more information

Validation errors not showing up - Rails 4

For some reason validation errors are not showing up.

my form

<%= form_for [@question.category, @question] do |f| %>

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

      <ul>
      <% @question.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  <div class="field panel">
    <%= f.label :question_type %><br>
    <%= f.select :question_type, [ ["single","single"],["multiple","multiple"] ], selected: f.object.question_type %>
  </div>
  <div class="field panel">
    <%= f.label :description %><br>
    <%= f.text_field :description %>
  </div>
  <div class="field panel">
    <%= f.label :image %><br>
    <% if @question.image? %>
      <div class="explanation-image text-center">
        <%= image_tag @question.image_url(:resized) %>
        <p>
          <label>
            <%= f.check_box :remove_image %>
            Remove image
          </label>
        </p>
      </div>
    <% end %>
    <%= f.file_field :image %>
    <%= f.hidden_field :image_cache %>
  </div>
  <div class="field panel">
    <%= f.label :explanation %><br>
    <%= f.text_area :explanation, size: "30x10" %>
  </div>
  <div class="field panel">
    <%= f.label :link_name %><br>
    <%= f.text_field :link_name %>
  </div>
  <div class="field panel">
    <%= f.label :link_url %><br>
    <%= f.text_area :link %>
  </div>
  <div class="field panel">
    <%= f.label :video_url %><br>
    <%= f.text_area :video_url %>
  </div>
  <div class="field panel">
    <%= f.label :category_id %><br><%= @category.title %>
    <%= f.hidden_field :category_id %>
  </div>
  <div class="actions">
    <br>
    <%= f.submit 'Submit', class:"button round success" %> <%= link_to 'Back', category_questions_path, class: "button round alert" %>
  </div>
<% end %>

this is the model

class Question < ActiveRecord::Base
  belongs_to :category
  has_many :choices
  mount_uploader :image, ImageUploader

  validates :description, length: {
    minimum: 6
  }
  validates :link, presence: true
end

and parts of the controller

def edit
    @category = Category.find(params[:category_id])
    @question = @category.questions.find_by(id: params[:id])
  end

def update
    respond_to do |format|
      if @question.update(question_params)
        format.html { redirect_to category_question_url(@question.category, @question), notice: 'Question was successfully updated.' }
        format.json { render :show, status: :ok, location: @question }
      else
        format.html {
          @category = Category.find(params[:category_id])
          @question = @category.questions.find_by(id: params[:id])
          render action: :edit
        }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
  end

the error messages code is directly from the scaffolding. i haven't touched it. if i try to edit a question and save it while lets say link field is empty it will reload the edit action correctly but no error message will pop up.

Any clues?

Has_man through: association for category_sizes

Hello i'm creating a clothing store. I have Categories that have Sizes. A Womens Shirt(category) might have XS, S, M, Large. A mens shirt can have XS, S, M, L. Shoes can have 4-16 and so on.

I have created a has_many through: association that connects the Category table with Sizes table by a Cateogry_Sizes table.

When admin creates a Category they should select all the sizes that category will need.

How can i select the sizes in the below view. The current code is incorrect? In console When i go category.sizes i just get an empty array

view

<div class="container">
  <div class=“row”>
    <div class="col-md-6 col-md-offset-3">
      <div class="panel panel-primary">
        <div class="panel-body">
                    <%= simple_form_for(@category) do |f| %>
                      <div class="form-inputs">
                        <%= f.input :name %>
              <%= f.select(:sizes, Size.all.map {|s| [s.title, s.id]}, :multiple => true) %>
              <%= f.collection_select :parent_id, Category.order(:name), :id, :name, {prompt: "Select Parrent ID If Applicable"},include_blank: true %>
              <div class="form-actions"><%= f.button :submit %></div>
            </div>
          <% end %>
        </div>
      </div>
    </div>
  </div>
</div>

Category model.

class Category < ActiveRecord::Base
    has_ancestry
    has_many :items
    validates :name, presence: true, length: { maximum: 20 }
  has_many :category_sizes
  has_many :sizes, through: :category_sizes
end

Size model

class Size < ActiveRecord::Base
    validates :title, presence: true, length: { maximum: 15 }
    validates :title, uniqueness: true

  has_many :category_sizes
  has_many :categories, through: :category_sizes
end

Category_size model

class CategorySize < ActiveRecord::Base
  belongs_to :category
  belongs_to :size
end

Schema

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

  create_table "categories", force: :cascade do |t|
    t.string   "name"
    t.string   "ancestry"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "categories", ["ancestry"], name: "index_categories_on_ancestry"

  create_table "category_sizes", force: :cascade do |t|
    t.integer  "category_id"
    t.integer  "size_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  add_index "category_sizes", ["category_id"], name: "index_category_sizes_on_category_id"
  add_index "category_sizes", ["size_id"], name: "index_category_sizes_on_size_id"

  create_table "items", force: :cascade do |t|
    t.string   "title"
    t.decimal  "price"
    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"
    t.integer  "category_id"
  end

  add_index "items", ["user_id", "created_at"], name: "index_items_on_user_id_and_created_at"
  add_index "items", ["user_id"], name: "index_items_on_user_id"

  create_table "sizes", force: :cascade do |t|
    t.text     "title"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "taggings", force: :cascade do |t|
    t.integer  "tag_id"
    t.integer  "taggable_id"
    t.string   "taggable_type"
    t.integer  "tagger_id"
    t.string   "tagger_type"
    t.string   "context",       limit: 128
    t.datetime "created_at"
  end

  add_index "taggings", ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true
  add_index "taggings", ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context"

  create_table "tags", force: :cascade do |t|
    t.string  "name"
    t.integer "taggings_count", default: 0
  end

  add_index "tags", ["name"], name: "index_tags_on_name", unique: true

  create_table "users", force: :cascade do |t|
    t.string   "username"
    t.string   "email"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.string   "password_digest"
    t.string   "remember_digest"
    t.boolean  "admin",               default: false
    t.string   "activation_digest"
    t.boolean  "activated",           default: false
    t.datetime "activated_at"
    t.string   "reset_digest"
    t.string   ">"
    t.datetime "reset_sent_at"
    t.string   "avatar_file_name"
    t.string   "avatar_content_type"
    t.integer  "avatar_file_size"
    t.datetime "avatar_updated_at"
    t.text     "description"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true

end