RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

I followed the tutorial and I'm able to show data, but I have a couple of issues probably about app/assets/javascripts/products.js.coffee file:

app/assets/javascripts/products.js.coffee
jQuery -> 
  $('#products').dataTable( {
    "sDom": "<'row'<'span3'l><'span9'f>r>t<'row'<'span8'i><'span12'p>>"
    "sPaginationType": "bootstrap",
    "bProcessing": true,
    "bServerSide": true 
    "sAjaxSource": $('#products').data('source')
  } );

1) I don't understand the "sAjaxSource": $('#products').data('source') param. If I try to remove this row nothing changes. Why ?

2) bootstrap layout doesn't work. Below my code:

Table def

app/view/products/index.html.erb
<table id="products" class="datatable table table-striped table-bordered" data-source="<%= products_url(format: "json") %>">```

``` app/assets/javascripts/application.js
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require bootstrap
//= require twitter/bootstrap
//= require dataTables/jquery.dataTables
//= require dataTables/jquery.dataTables.bootstrap3
//= require products
//= require turbolinks
app/assets/stylesheets/application.css
 *= require_self
 *= require jquery.ui.core
 *= require jquery.ui.theme
 *= require dataTables/jquery.dataTables.bootstrap3
 *= require dataTables/extras/TableTools
 *= require dataTables/extras/TableTools_JUI
 *= require_tree .

Any idea is very appreciated. Thanks

Avatar

actually nvm i figured it out I just used a form_for :car(replace with your model name)

then call current_user.create_car etc... in my profile controller.
with added strong param for car params

now I'm wondering if I can make this cleaner with method mission or delegate so I don't have to chain methods so much in controller

Avatar

I added some extra logic to not add the delete members when destroy is not included. Supports both only and except route options.

ruby
# This module adds delete URL helpers to allow resource deletion
# without using JavaScript to create destroy request
module DeleteResourceRoute

  def resources(*args, &block)
    super(*args) do

      add_delete_members = true

      args.each do |arg|
        add_delete_members = false if arg.is_a?(Hash) and (
                                        (arg.has_key?(:only) and !arg[:only].include?(:destroy)) or
                                        (arg.has_key?(:except) and arg[:except].include?(:destroy))
                                      )
      end

      if add_delete_members
        yield if block_given?
        member do
          get     :delete
          delete  :delete, action: :destroy
        end
      end

    end
  end

end
Avatar

does any one know how to make something like this work with 2 none nested models? for example I have user model that has one profile(model) and one car(model)

both profile and car models are nested under user but car and profile has no relationship. I figure I can do a form_for user and use both field_for profile/car but is there a better way to do this?

Avatar

How did you solve the issue? I am having the same problems. I'm currently using .getAttribute('data-orders'), and that seems to work fine, but it is still not displaying.

Avatar

Thanks for this Dave, I had a hard time tracking this problem down until I found your comment.

Avatar

Great episode, as usual.

Is there any way to make this work for multi-word tags?

My index page works fine with one-word tags (e.g. 'superman', 'comic', etc.), but when I have a multi-word tag (e.g. 'the riddler', 'the penguin', etc.) I get the following error:

undefined method 'joins' for []:Array.

When I try to filter my articles by the tag 'Tag 3', the URL that I am directed to is:

http://localhost:3000/tags/Tag%203

I imagine it has something to do with this line:

rails
<p>Tags: <%= raw @article.tag_list.map { |t| link_to t, tag_path(t) }.join(", ") %></p>

Anyone know how to make this work with multi-word tags?

Avatar

Hi, I am using carrier wave for file upload

ruby
class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick
  storage :file
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end
end

Here my question is how to specify the tenant.id like

"uploads/#{current_tenant.id}/#{model.class.to_s.underscore}
/#{mounted_as}/#{model.id}"

where current_tenant is a application controller helper method

Thanks

Avatar

Can a single user be subscribed to multiple channels and stay subscribed so long as they're logged in? Even if they navigate to a different page? Maybe in the application layout I should add

ruby
<%= @channels.each { |c| subscribe_to c } %> 

? thx!

Avatar

As per the Rails 4 docs performance tests are no longer part of the default stack.. You need to add the rails-perftest gem:

gem 'rails-perftest'

Avatar

What got me in this was editing my own /etc/host file to have '127.0.0.1' point to my own custom wildcard domain '*.local.me'

After some research, I discovered you can't have a wild card in your /etc/host file. When Ryan says to use 'lvh.me:3000', literally use that rather than editing your /etc/host file. You can then use your subdomains.

Also, since we're on Rails 4 now, check out:

http://railscasts.com/episodes/123-subdomains-revised

Avatar

Thanks Tim! This worked for me as well!!

Avatar

Srdan I've put it working without much problems few days ago. I've wondering how to show the amount the user is going to pay on sandbox. Thanks!!

Avatar

I followed the tutorial and put all the required gems in the Gemfile as people suggested. I've been experimenting for hours now and after doing rails generate bootstrap:install - I get no change in fonts or formatting and it stays that way no matter what I do..
I'm using Rails 3.2.6 and Ruby 1.9.3

Avatar

If you remove the csrf_meta_tag from cached pages wouldn't that mean that those request is not safe against CSRF attacks? Is their any way to solve this problem?

Avatar

Why not just use Capistrano for deployment, and use a before stop hook and first stop monit, then after start, start monit?

Avatar

I get this error after putting in the rescue code(which does not work for me)

"SyntaxError: missing ", starting #line 7 .." in my facebook.js.coffee.erb file. Obviously that is not where the syntax error is and it is triggered by somethings else but I cannot find it.

Anyone an idea why the rescue won't work? Everything else in the episode before the rescue part works but not after.

Avatar

Never mind. . . it was a stupid oversight; my deploy script doesn't run migrations automatically (which I gotta fix) so the fix was simply to run a manual migration on prod:

bundle exec rake db:migrate RAILS_ENV=production

Avatar

Useful but maybe a revised version could be awesome

Avatar

I prefer this approach to that of StrongParameters, which is now part of Rails4. Anyone have an idea of how this approach compares to SP? I ask because this episode was produced after your StrongParameters episode.

Avatar

Thank you. I was able to get it working with Rails 4.

Avatar

Can you post the full unicorn init you are using?

Avatar

This is interesting. What do this end up doing to your schema.rb file? That is, if you were to launch a new server and needed to get the DB set up (for the first time), would you have to run thru all the migrations, or could you still do db:schema:load?

Avatar

You say:

"It’s a good idea to use a time zone that matches the one where most of our app’s users are located"

Why is that? As also noted, it's a good idea to use a different time zone for development so errors aren't obfuscated. So why not just leave config.time_zone at UTC? It seems like setting current time zone is only useful when all users are in the same time zone. Otherwise, it just adds complexity. Am I missing something?

Avatar

Not sure if this was mentioned yet. but fetch no longer triggers reset by default.

ruby
@collection.fetch(reset: true)

This fixed my problem^

Avatar

Can I use presenters to clean up a view that does not have a corresponding model (e.g. my Home page, static_pages#home)? If so, how would I set up the presenter class? Thanks!

Avatar

@Dimitri have you found a solution for this issue? Thanks

Avatar

After bundle installing the gems, and adding

coffeescript
jQuery ->
  $('task_sessions_table').dataTable()

in the appropriate coffee file (app/assets/javascripts/), just like Ryan did, I try to reload the page and get the error.

couldn't find file 'dataTables/jquery.dataTables'
(in /Users/Jonathan/code/gp-taskmanagement/app/assets/stylesheets/application.css.scss:7)

Please help!

Avatar

With Doorkeeper 0.7.4 I had to use callback = "urn:ietf:wg:oauth:2.0:oob" in place of the localhost:3001 callback. Otherwise, the page to exchange the authorization token for an accepted authorization code complained of a bad callback url.

Avatar

Is there a way to save a record skipping the counter_cache callback?

I'm uploading some pictures via Carrierwave and would like to trigger the reset_counters after all my batch uploading has finished.

Avatar

Things seem to have moved around for Rails 4. I had to change the class/module as follows:

ruby
class ActiveSupport::Logger::SimpleFormatter
  def call(severity, time, progname, msg)
    "[#{severity}] [#{time}] #{msg}\n"
  end
end
Avatar

For error: "This transaction cannot be processed due to an invalid merchant configuration."

Go to developer.paypal.com, register with your normal PayPal account, tab Applications than click on Sandbox Accounts, find your seller account click on him and hit profile.
Under profile tab change Account type to Business-Pro.

Avatar

I was able to get it working by following your blog post. I simplified the code a bit:
Syntax Highlighting using Rouge in Rails 4 Check it out:

Avatar

How to syntax highlight the code? I see class='ruby' in the view code. Where is the CSS?

Avatar

You should not use the match method in your router without specifying an HTTP method.

Match is now depreciated with rails 4. I changed "match" to "get". I figured it makes sense to only support get in these routes. Who would be posting or patching in an unknown language?

ruby
# match '*path', to: redirect("/#{I18n.default_locale}/%{path}"), constraints: lambda { |req| !req.path.starts_with? "/#{I18n.default_locale}/" }
# match '', to: redirect("/#{I18n.default_locale}")

get '*path', to: redirect("/#{I18n.default_locale}/%{path}"), constraints: lambda { |req| !req.path.starts_with? "/#{I18n.default_locale}/" }
get '', to: redirect("/#{I18n.default_locale}")
Avatar

I have updated the links in the show notes. Thanks for letting us know! :)

Avatar
  • in case anyone wants to use VCR for just a piece of a larger test suite, VCR blocks any unapproved HTTP access- and will get in the way of the other tests and they will fail with a warning from VCR (unless hidden behind a rescue block-another story). This was unexpected for me- I want to pick and choose which tests are recorded. I was thinking that the :all option would work, but do not desire to signup for housecleaning on all of the recorded cassettes.

VCR behavior can be modified with the flag set in the config block:

in vcr_config.rb
c.allow_http_connections_when_no_cassette = true

and pass through is allowed for these tests, and what I want.

I hope this helps someone else- this is a great tool thank you so much this cast and this gem.

Avatar

I am a bit curious about why do we send the user to the :new action instead of the :edit action when they want to become a full member?

Avatar

@Ryan
Great cast!
Just wanted to ask, cast is from 2009, is there any major changes to this today, or i can go to production with this solution without problems?

Avatar

In order for authorize_request and deauthorize_request to work, you have to set the authorize mode to whitelist.

application.rb
Rack::MiniProfiler.config.authorization_mode = :whitelist

Avatar

Thanks Myron: Now my vcr_config looks like this from Ryan's:

vcr_config.rb:

vcr_config.rb
require 'vcr'

  VCR.configure do |c|
    c.cassette_library_dir = Rails.root.join("spec", "vcr")
    c.hook_into :webmock
    c.configure_rspec_metadata!
    #was :webmock
    #c.filter_sensitive_data('<WSDL>') { "http://www.webservicex.net:80/uszip.asmx?WSDL" }
  end

  RSpec.configure do |c|
    c.treat_symbols_as_metadata_keys_with_true_values = true
#    c.around(:each, :vcr) do |example|
#      name = example.metadata[:full_description].split(/\s+/, 2).join("/").underscore.gsub(/[^\w\/]+/, "_")
#      options = example.metadata.slice(:record, :match_requests_on).except(:example_group)
#      VCR.use_cassette(name, options) { example.call }
#    end
  end

and spec_helper.rb has changed the fakeweb include to webmock

spec_helper.rb
require 'webmock/rspec'
Avatar

this guy makes the same but updated to use strong_parameters :

http://iroller.ru/blog/2013/10/14/nested-model-form-in-rails-4/

hope this help someone.