RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

If you have an issue with assets compiling as I did--no css or javascript (eg. no alert box on destroy) solution is to bump up Rails version to 3.2.14 and run bundle install.

Details are here:
http://stackoverflow.com/questions/18005115/why-are-js-files-in-my-rails-asset-pipeline-not-being-compiled

(Interesting to learn how destroy requires Javascript to get a delete request (Started DELETE). )

Avatar

Has anybody managed to crop images while using porstgresql as a database?

Avatar

My js replaces the elements on the dom with the correct code, however the new image doesn't render on the page. The file IS in the correct directory, and the paths match. When I reload the page the image will render.

Why is this happening and how can I fix it?

Thanks!

Avatar

@Ste Just to clarify, this is Ruby on Rails, NOT PHP. They're completely different, so this is probably the wrong place if you're looking for specific copy-and-paste examples (but the concept might still apply, I'm not quite sure).

Avatar

if you get

method_missing': undefined method `attr_accessible' for User (call 'User.connection' to establish a connection):Class (NoMethodError)

it may be fixable by installing the "protected_attributes" gem.

Avatar

Here's what I ended up doing to test my models. Other thoughts and ideas are welcome (like a shared example to use on all account scoped models based on this gist)

ruby
  let(:account1)     { create(:account) }
  let(:account2)     { create(:account) }
  let(:transaction1) { create(:transaction, account: account1, user: account1.owner) }
  let(:transaction2) { create(:transaction, account: account2, user: account2.owner) }

  describe "default scope" do
    context "query with no account set" do
      it "returns an empty array" do
        expect(Transaction.all).to be_empty
      end
    end

    context "query in account1" do
      it "returns only account1's transaction" do
        Account.current_id = account1.id
        expect(Transaction.all).to eq [transaction1]
      end
    end

    context "query in account2" do
      it "returns only account2's transaction" do
        Account.current_id = account2.id
        expect(Transaction.all).to eq [transaction2]
      end
    end
  end
Avatar

Okay, so I am using the Carrierwave gem to upload the file, how would the process of importing the file then differ? He was just storing it in the temporary files, but I am storing the files using Carrierwave. I would this change the import method in the controller?

Avatar

Does not work with rails 4.2 for me.
I've setup the db and inserted the sample data but the second select field does not appear after choosing a country.

Avatar

My take on that issue is that it is indeed on by default if that column exists in the database. However it looks like turning it off is broken.

Avatar

Check me if I'm wrong. Follow my understanding, in rails 4.2 it automatically uses this technique, is that right? https://github.com/rails/rails/issues/19042

Avatar

hi
I get this error while using nested resorces in my new action .
undefined method `fetch_value' for nil:NilClass
can you help me ?
Thanks Ryan!

Avatar

One doubt. My application before going to paypal first shows a form that takes some information from the user. Once this information is saved in the database, then I redirect to paypal site. So my controller uses this code

ruby
#code that  saves the cart in db
redirect_to @morder.paypal_url(store_url,hook_path,@cart.id)

So now i added encryption just as you said and would like to send the values, but I am getting an error.

ruby
#Same code as yours
values = encrypt_for_paypal(values)
    "https://www.sandbox.paypal.com/cgi-bin/webscr?" + values.to_query#Error displayed here says "wrong number of arguments"
  end

PAYPAL_CERT_PEM = File.read("#{Rails.root}/certs/paypal_cert.pem")
APP_CERT_PEM = File.read("#{Rails.root}/certs/app_cert.pem")
APP_KEY_PEM = File.read("#{Rails.root}/certs/app_key.pem")


  def encrypt_for_paypal(values)
    signed = OpenSSL::PKCS7::sign(OpenSSL::X509::Certificate.new(APP_CERT_PEM), OpenSSL::PKey::RSA.new(APP_KEY_PEM, ''), values.map { |k, v| "#{k}=#{v}" }.join("\n"), [], OpenSSL::PKCS7::BINARY)
    OpenSSL::PKCS7::encrypt([OpenSSL::X509::Certificate.new(PAYPAL_CERT_PEM)], signed.to_der, OpenSSL::Cipher::Cipher::new("DES3"), OpenSSL::PKCS7::BINARY).to_s.gsub("\n", "")
  end

The error is wrong number of arguments (0 for 1)

Avatar

I am trying to run the project i downloaded from the above given link. When i run "rake setup" I am cleary getting some compatibility erros since I am running the latest version of rails. How to fix this?

rake aborted!
LoadError: cannot load such file -- initializer
/home/vishal/Study/Agile Web Rails/store/config/boot.rb:54:in `load_initializer'
/home/vishal/Study/Agile Web Rails/store/config/boot.rb:38:in `run'
/home/vishal/Study/Agile Web Rails/store/config/boot.rb:11:in `boot!'
/home/vishal/Study/Agile Web Rails/store/config/boot.rb:109:in `<top (required)>'
/home/vishal/Study/Agile Web Rails/store/Rakefile:4:in `<top (required)>'
(See full trace by running task with --trace)
vishal@vishal-Rev-1-0:~/Study/Agile Web Rails/store$ rake setup --trace
rake aborted!
LoadError: cannot load such file -- initializer
/home/vishal/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121:in `require'
/home/vishal/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:121:in `require'
/home/vishal/Study/Agile Web Rails/store/config/boot.rb:54:in `load_initializer'
/home/vishal/Study/Agile Web Rails/store/config/boot.rb:38:in `run'
/home/vishal/Study/Agile Web Rails/store/config/boot.rb:11:in `boot!'
/home/vishal/Study/Agile Web Rails/store/config/boot.rb:109:in `<top (required)>'
/home/vishal/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/vishal/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/vishal/Study/Agile Web Rails/store/Rakefile:4:in `<top (required)>'
/home/vishal/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rake/rake_module.rb:28:in `load'
/home/vishal/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rake/rake_module.rb:28:in `load_rakefile'
/home/vishal/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rake/application.rb:689:in `raw_load_rakefile'
/home/vishal/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rake/application.rb:94:in `block in load_rakefile'
/home/vishal/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rake/application.rb:176:in `standard_exception_handling'
/home/vishal/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rake/application.rb:93:in `load_rakefile'
/home/vishal/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rake/application.rb:77:in `block in run'
/home/vishal/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rake/application.rb:176:in `standard_exception_handling'
/home/vishal/.rbenv/versions/2.2.1/lib/ruby/2.2.0/rake/application.rb:75:in `run'
/home/vishal/.rbenv/versions/2.2.1/bin/rake:33:in `<main>'

Avatar

Hi, I have the same problem, too.
How did you fix it? thanks.

Avatar

Have you tried for model for devise gem. I am not able to save it.

Avatar

This video was quite handy when I upgraded Smartlend to Rails 4. Thanks!

Avatar

What if we have something like

class CouponController < ApplicationController
  def index
    @coupons = Coupon.all.page(params[:page])
    @coupons = @coupons.for_amount(params[:amount]) if params[:amount].present?
    @coupons = PaginatingDecorator.new(@coupons)

    respond_with(@coupons) do |format|
      format.html
      format.csv { render :text => coupons_csv }
    end
  end

 private

  def coupons_csv
    column_names = %w(code name id amount expiration_date)
    CSV.generate do |csv|
      csv << column_names
      @coupons.each do |coupon|
        csv << column_names.map{ |attr| coupon.public_send(attr) }
      end
    end
  end

Here in coupons_csv I'll not receive the entire coupon list - I'll receive only the paginated set.So what would be the best way to get ALL filtered coupons into the csv and get per-page#paginated coupons in the index page?

Avatar

thanks for this, didn't expect I wouldn't need to create an unnecessary model and use any file storage gems. very informative on how params work as well.

Avatar

For me, the following worked:

ruby
elsif @user.update_attributes(params.require(:user).permit(:password, :password_confirmation))

I get it from:
http://stackoverflow.com/questions/17568062/activemodelforbiddenattributeserror-in-passwordresetscontrollerupdate

Avatar

Has anyone worked on an edit/update possibility for this episode?

Avatar

Was this behavior deprecated at some point?

Avatar

Foreman has a major flaw that makes it a non-starter for me: it can't handle different commands for starting and stopping a service. It also doesn't allow for different environments without using a wrapper shell script.

Avatar

Hey,
When I first try lvh.me:3000, it is working fine. But now I have problem with lvh.me:3000 it does not work any more, do you know how to solve this. I've been try on google but I cannot found any solution.
Thx.

Avatar

Hi Ryan, for more complex requests where you need to specify the child and sub-child tags, ie. when the request value(s) needed are located / nested down the xml tree - how would you write this code with Savon?

Avatar

Hi Ryan, thanks very much for putting up your soap_app built with Rails 4, it really helped with another Soap project I'm working on!

Avatar

So, after getting this form created can anyone point me in the direction of how to make it functional for a user to fill out? I am stuck! I'd like to have a radio button to select the answer from each group of possible answers and then make it submittable.

Avatar

I <3 you. Thank you! Nesting the attributes for the answers INSIDE of the attributes for the question inside of the parameters for the survey... I never would've figured it out in a million years.

Avatar

Would I need to add the params for the answer to the survey class or to the questions class?

Avatar

So I am trying to get this set up for my AWS EC2 instance, I currently have 2 tiers (staging / prod) and deploying with capistrano. Followed the tutorial video and some other tutorials elsewhere to supplement

Looking for some expert input on my approach and pointing out things that I might be missing. I manage to get Redis / sidekiq installed on the staging instance ( as I am confirming this works before moving onto production ).

I have one worker EmailSender

ruby
class EmailSender
  include Sidekiq::Worker
  sidekiq_options retry: true, queue: "high"
  
  def perform(email_hash)
    stuff
  end
end

my deploy.rb

ruby
namespace :deploy do
  task :start, :roles => :app do
    run "touch #{current_path}/tmp/restart.txt"
    run "touch #{current_path}/log/sidekiq.log"
    run "cd #{current_path}; bundle exec sidekiq -d L log/sidekiq.log -C './config/sidekiq.yml'"

Then my sidekiq.yml

ruby
:verbose: false
:pidfile: ./tmp/pids/sidekiq.pid
:logfile: ./log/sidekiq.log
:concurrency: 25
:queues:
  - [high, 5]
  - [default, 1]

When I deployed, it correctly brings up the sidekiq instance - which I can confirm via ps aux | grep sidekiq...

But when I try to process the emailsender job...it seems like it isn't doing anything, wondering if anything above or if I am missing causing the job to not be picked up?

I tried to the perform job manually and it works.

Thanks!

Avatar

Curious if this is still a valid way of using the Enum in Rails 4.1? Really want to have something defined on a model without creating a second model -- it's static a static list of locations --this seems like the best way of dealing with it.

Avatar

Does anyone know of a tutorial that is more up-to-date with Rails 4. I'm having problems figuring out how to a simple CRUD with the strong parameters.

Avatar

You should have to pass @snippet instead of snippet_id.

By this you don't need to again

snippet = Snippet.find(snippet_id)

Avatar

Thanks. Works perfectly for me as well. To who ever uses this method, don't forget to render the pdf as I hadn't first time round and crashed my browser...

Avatar

For those trying, if have not already, to sort by association or be more specific with which columns can be sorted;

ruby
  def sort_column
    acceptable_cols = ["users.name", "users.email", "addresses.city", "addresses.state"]
    acceptable_cols.include?(params[:sort]) ? params[:sort] : "name"
  end

Just specifying an array of the allowed columns, rather than relying on the columns defined by the model allows you better control

I don't know if this is the best solution, I'm about two weeks new to Ruby and RoR.

Avatar

After a lot of time on google, I think I finally got this addressed:

add content_type to upload_helpber.rb (fields method and policy_data method):

ruby
def fields
  {
    :key => key,
    :acl => @options[:acl],
    :policy => policy,
    :content_type => nil,
    :signature => signature,
    "AWSAccessKeyId" => @options[:aws_access_key_id],
  }
end

def policy_data
  {
    expiration: @options[:expiration],
    conditions: [
      ["starts-with", "$utf8", ""],
      ["starts-with", "$Content-Type", ""],
      ["starts-with", "$key", ""],
      ["content-length-range", 0, @options[:max_file_size]],
      {bucket: @options[:bucket]},
      {acl: @options[:acl]}
    ]
  }
end

add the two lines above "data.submit()" in the add method in the coffeescript file

coffee
add: (e, data) ->
  ...
   $('#fileupload').append(data.context)
   data.form.find('#content_type').attr('name','Content-Type')
   data.form.find('#content_type').val(file.type)
   data.submit()
Avatar

I am also looking to do the same thing. How can you link three dropdown that are dynamic?

Avatar

First Off this this a very good tutorial. But i am having some Issues with the select fields and they are not being populated correctly on the nested fields

One of my nested Form Fields:

If i do this i get the year correctly and populated

<%= f.text_field :year %>

But what do i pass in this select field to populate the correct year.

I know it will be a second input in the option_for_select but how to i get the object that is being inputed

f.year Does Not Work..

<%= f.select :year, options_for_select((1900..Date.today.year+1).to_a.reverse), {:prompt => 'Year', :class=>"pointer" } %>

Avatar

No idea why but I needed to change:

$(this).closest('fieldset').hide()
into:
$(this).parent().hide()

for the removing to work.

Avatar

Ken, you are a champ! I've been working on this railscast for over 5 hours and kept getting no data on the y axis. Super frustrating, especially when Ryan demos his solution works with only .first.try(:total_price)

Any ideas on why Ryan's demo works in that format? I'm on win 7, rails 4.2

:)