RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

Hi admin. I use Ruby 1.9.3 When I run this code. I met warning:
'''
Warning:C:/Users/T410/Desktop/chinsu/config/application.rb:3:in `': iconv will be deprecated in the future, use String#encode instead.'''
And when I lick button import in browser I met Error:
'''
Errno::EBADF in ProductImportsController#create

Bad file descriptor - C:/Users/T410/AppData/Local/Temp/RackMultipart20141104-5028-kjmbt6
app/models/product_import.rb:49:in new'
app/models/product_import.rb:49:in
open_spreadsheet'
app/models/product_import.rb:36:in load_imported_products'
app/models/product_import.rb:32:in
imported_products'
app/models/product_import.rb:18:in save'
app/controllers/product_imports_controller.rb:8:in
create'
'''

Avatar

Did you find out how to solve this? I have the same problem here.

Avatar

It looks like there is a collection_check_boxes in Rails 4 that should make this all a lot easier?

Avatar

Maybe that's changed. In Office 2013 I can open the XML file (with a warning) if it has a .xml extension, but Excel rejects it completely if I rename it to .xlsx.

Avatar

Saich, I hope you haven't been waiting all this time, but if others have the same issue: append "/refinery" (without the quotes) to your url to get to the backend, or dashboard.

Avatar

I am using Rails4, but has not problem as you described above
I am using ruby 2.0, rails 4.0.4

Avatar

Thank you Andris, It works well for me in Rails4

Avatar

I had a lot of issues getting Fog to work correctly and fortunately just found this, which is more specific to the purpose here anyway:

https://github.com/sorentwo/carrierwave-aws

Hope that helps.

Avatar

Has anyone tried testing this with rspec

Avatar

thanks @Bardwin for sharing! This works great but I want to hide the pagination on every page vs just the very last page and simply have the "Show more products" button on each page. Any ideas on how to accomplish that?

Currently my index.js.erb is below

$('#items').append('<%= j render('items') %>');
<% if @items.next_page %>
$('.pagination').replaceWith('<%= j will_paginate(@items) %>');
<% else %>
$('#append_and_paginate').remove();
<% end %>
<% sleep 1 %>

Thanks again.

Avatar

Coderay documentation sucks so much. Where can I find which $number maps to which langauge? What about other options for the div? How do programmers even find this stuff out? Digging through the mess of the source code?

What the heck is textile, and why is it impossible to find any source that actually explains it, instead of just off-handedly mention it as if everyone knows what it is, and when you use it? Why do we need redcloth and we do we need textile? Assumpetions.

Do they even want people to use it? Why would you not make the documentation better. Why make it so complicated, and obscure to find out how to use it?

Avatar

User creation needs to be modified slightly to play nicely with the new strong parameters in Rails 4. This error happens in 4.1.5 and might have been recent.

Issue and fix at stackoverflow

where(auth.slice(:provider, :uid)) needs to be
where(provider: auth.provider, uid: auth.uid)

Avatar

On rubygems that latest update is June 2013 and it is presently at a failing rating on GitHub. Is this something of a concern or can this gem still be used safely in production?

Avatar

Important note. Database extensions and index creation (at least for Postgres ones like those used in this episode) are supported since Rails 4 so there should be no need to switch to structure.sql as advised in this episode anymore.

See this Pull Request merged over a year ago.

Avatar

Hi guys,
Is there a way to use LDAP to authenticate users without them keying in Login credentials. i.e the Rails Application should fetch windows domain and should match it with the details in Active directory and allow the user into the application if its a valid Active Directory entry. I am able to login using username password. but nnow trying without username password.

Thanks in advance

Avatar

The more correct variant of this approach (using a data- attribute) was already covered the screencast. Nothing to see here. Move along.

Avatar

Hi i have to search the attributes which is there in some other model and i want to search multiple attributes

index view

<%= form_tag issue_slips_path, :method => 'get' do %>

<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>

<%end%>

controller

@issue_slip = IssueSlip.search(params[:search])

model
def self.search(search)
if search
find(:all, :conditions => ['store_location_id LIKE :search ', {:search => "%#{search}%"}])
else
find(:all)
end
end

the store location name is what i have to search but i have only the id, how to search the name which is there in another StoreLocation model please help

Avatar

Great episode! There are two more Rack middlewares as of rails 4.1.0:

Rack::Sendfile
- serves public files directly from the http server (nginx, apache, etc)

ActiveRecord::Migration::CheckPending
- verifies that all migrations have been run before loading a web page

Avatar

Update for anyone watching this, use these updates in purchase.rb:

require "rubygems"
require "active_merchant"
require "active_merchant/billing/rails"
 ...

credit_card = ActiveMerchant::Billing::CreditCard.new(
    :brand               => "visa",
Avatar

If you face the problem with mongoid problem:

MONGO MOP Can't canonicalize query: BadValue unknown operator: $oid

Make sure you change current_user method:

   def current_user
-    @current_user ||= User.find(session[:user_id]) if session[:user_id]
+    @current_user ||= User.find(session[:user_id]["$oid"]) if session[:user_id]
   end

https://github.com/liziane/Cookbook/commit/128a9aeee392b8e680d86fdad35ac258846cedd6

Avatar

After all of these years, no one ever noticed complete(comlpete) is spelled wrong :>)

Good lesson though.

Avatar

I got undefined method `javascript' when I follow along. It does not loke <% javascript :defaults, 'endless_page' %>. What is going on?

Avatar

if you are getting empty values:

Stripe error while creating customer: You passed an empty string for 'card'. We
assume empty values are an attempt to unset a parameter; however 'card' cannot b
e unset. You should remove 'card' from your request or supply a non-empty value

  1. Turn Off Turbolinks - wrap your links to the subscription form with no-data-turbolink. Turbrolinks is not re-loading the subscription.js.coffee on page load, so the code dosen't load the card values.
<div data-no-turbolink> <%= link_to 'New Subscription', new_subscription_path %></div>
  1. update to stripe v2
<%= javascript_include_tag "https://js.stripe.com/v2/", 'application', 'data-turbolinks-track' => true %>

Drove me crazy!

Avatar

I had the same problem. Turns out that scoped has been deprecated and the replacement is where(nil).

This StackOverflow posting has more details.

Avatar

These drop down menus are really often used these days.. A lot of websites do use them. Rail seems to be a management system like drupal.
A cool slide menu is used at this site here http://www.nitis-flotte-kindermoden.de Its uses another system (a shopping system) from cosmoshop.
But I think all systems are based of Javascript?!

Avatar

This approach is used on our app and currently we are having troubles whenever a gem we are using raises an error - instead of an error message we are getting nginx Bad Gateway pages and nothing in the log and the ErrorsController show action does not get run at all (Could be for another reason and not due to this approach at all - not sure - just seems likely)

Avatar

In Rails 4.1, we can no longer use this line:

validates_inclusion_of :time_zone, in: ActiveSupport::TimeZone.zones_map(&:name)

It needs to be:

validates_inclusion_of :time_zone, in: ActiveSupport::TimeZone.zones_map(&:name).keys

as discussed here

Avatar

Did you guys figure it out? I'm stuck too!

Avatar

If you use a session, then doesn't that mean the default devise signup can no longer be used until that session is deleted? I don't see where the deletion is handled. Since using a provider uses the new user registration path, that means the new user registration path can no longer be used to default devise login. Even refreshing with cache clearing doesn't clear a session.

Avatar

Where is your method "scoped" defined at in your def.self.text_search(query) ?

And exactly how did you define it?

Avatar

Worth noting that at the end of products_controller.rb you'll need to add :released_on to get through the param filter,

ruby
    def product_params
      params.require(:product).permit(:name, :price, :released_on)
    end
Avatar

Use figaro gem. https://github.com/laserlemon/figaro
This solution is much easier, and cleaner, and easier to maintain than secrete.yml in my opinion.

set keys in application.yml which figaro specifies you create, and set keys in that file like so

FACEBOOK_SECRET: '13103103779'

Then it will be available to access throughout your application with the syntax like so

provider :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_SECRET']

If you're using Devise, put the above line in the devise.rb initializer file, and not the omniauth.rb initializer file. When using Devise and omniauth together, you don't need an omniauth.rb file. The syntax for the devise way is this

config.omniauth :facebook, ENV["FACEBOOK_APP_ID"], ENV["FACEBOOK_SECRET"]

Avatar

Update rubber-passenger.yml. Set:
passenger_version: '1:4.0.53-1~precise1'

Avatar

I resorted to using shadow columns in my tables to resole this issue. DBA's might hate it, but I didn't see another choice. That is true especially since I have polymorphic tables that could never be directly referenced any other way within my experience.

Basically, I added columns to the table of name xxshadow. These are used solely to support datatables search and sort.

In my model, I use

after_update :shadow_update.

And, that method is:

  def shadow_update
    # After record is updated, update shadow columns if needed and force an update to write them
    # This actually triggers after create as well, but with correct timing
    # Since all columns are updated to resolve differences, one update should resolve all
    # Incorrectly coded, you can infinitely loop on the update
    if [self.yrshadow, self.mkshadow, self.mdshadow, self.coshadow, self.stshadow] != [self.year, self.make, self.model, self.color, self.status]
      self.yrshadow = self.year
      self.mkshadow = self.make
      self.mdshadow = self.model
      self.coshadow = self.color
      self.stshadow = self.status
      self.save!
    end
Avatar

UPDATE: Rails 4 support was just merged into this, so it should work with Rails 4 now.

Avatar

i got the mistake. I installed the gem 'protected attributes'. I also forgot to define the attr_accessible. The working version in Rails 4 looks so:

ruby
attr_accessible :id, :url, :price_ek
def self.import(file)
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      product = find_by_id(row["id"]) || new
      product.attributes = row.to_hash.slice(*accessible_attributes)
      product.save!
    end
  end

  def self.open_spreadsheet(file)
    case File.extname(file.original_filename)
    when ".csv" then Roo::Csv.new(file.path, csv_options: {col_sep: ";"})
    when ".xls" then Roo::Excel.new(file.path)
    when ".xlsx" then Roo::Excelx.new(file.path)
    else raise "Unknown file type: #{file.original_filename}"
    end
  end
Avatar

Hi Shotsoft, I had the same problem as you, if you remove:

attr_accessor :email, :password, :password_confirmation

from user.rb

and add

ruby
  private
    def user_params
      params.require(:user).permit(:email, :password, :password_confirmation)
    end

to the end of users_controller.rb it should work. See Andreas Bjørn Hassing Nielsen's (above) reply for more information.

Once you've done this you just need to modify the create method so that is has

@user = User.new(user_params)

Avatar

Kaminari seems to not have the prev_span_tag and the prev_span files.

It uses certain methods to reference the partials but the ones for disabled ones are missing. So how do we create a method to reference a custom disabled partial we make from scratch?

Avatar

It is definitely been enlightening, service object approach can be much more simplified with the help of this episode..

Avatar

Interesting and useful episode, thanks!

Avatar

Thanks, that was just what i needed! Having faced design loader,service authorization and presenters.. This really helped me, i am going to recommend my peers to go through this episode too!

Avatar

Great Railcast,

Besides a couple of shortcomings, which i think can be fixed with time, it has taught us how to save on time while testing, hence making work a whole lot easier