RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

Great episode! It would have been nice to see you limit the @articles query to grab articles in the current month as well, but that's not too hard.

Avatar

Fantastic. Timely. I'm working at revising an app we use to schedule assignments in our small photo business. (Internal use, not client-facing.) I'm using FullCalendar for the calendar but I am really getting frustrated by not being able to find a dateTIMEpicker that's as clean and sophisticated as the jQueryUI datepicker. I don't care much for the ones I've seen that use a slider for the hour/minute, and the one I used for the original version of this app is pretty out of date. Anyone have any suggestions? I'm fine with a select widget for hour/minute, but it needs to be integrated within the popup calendar widget. I'm about ready to settle for a simple text entry field (with Chronic) instead, ispired by the Virtual Attribute revised episode from a short while back.

I really love what you have demonstrated about making a calendar from scratch. I think I'll stick with FullCalendar for my project though, because I need event blocks to overlap (to indicate schedule conflicts) and to be able to colorize different types of events (confirmed, tentative, staff appointments...)

Thank you so much, Ryan!

Avatar

I'm having the same problem, any clues?

Avatar

Naturally, I figured out the answer immediately after asking for help.

I needed to add the scope parameter to the JS:

javascript
FB.login(
  function(response) {
    if (response.authResponse) {
      return window.location = '/auth/facebook/callback';
    }
  }, { scope: 'email' }
);
Avatar

After dropping down to the 1.4 version of omniauth-facebook, I no longer receive the user's email in the auth hash. I tried adding :scope => 'email' to the OmniAuth provider config, but to no avail.

Anyone have an idea?

Avatar

I'd like to be able to create two objects, A and B, and relate them both to Object C in my factories so I can dry up my code. How can I do that using factory girl?

I'm running into scenarios where Object A is related to one instance of Object C, and Object B is related to another instance of Object C, when I'd like them to both be relating to the same instance of Object C.

Avatar

That totally exists now. They're called Batch Actions :]

Avatar

Kind of. It will sort by the ids of the parent model, instead of something more useful (like alphabetical sorting).

Avatar

Perhaps because you're not using the add function? The below format works fine for me.

ruby
validate :name_must_be_cool

def name_must_be_cool
  errors.add(:name, 'Try again!') unless is_cool?(name)
end
Avatar

The command rails g active_admin:resource product doesn't actually create a model; it just creates the app/admin/products.rb file so Active Admin renders a GUI for this resource when you start your server. You've got to run rails g model product first.

Avatar

Assigning before_create (etc) callbacks in your model work just fine with ActiveAdmin. What exactly is your problem?

Avatar

+1, I'm curious to hear more about why Ryan prefers writing SQL within migrations.

Avatar

my error when I'm trying to get total_votes:

ruby
PGError: ERROR:  relation "album_votes" does not exist

what's wrong?

Avatar

May I have a question: why don't you store card_number and card verification value in database?

Avatar

Me too got the error message "There's an error with this transaction. Please enter a complete billing address." but it seems there's no :billing_address option in credit card settings http://activemerchant.rubyforge.org/classes/ActiveMerchant/Billing/CreditCard.html

any ideas?

Avatar

Having the same issue on a windows host using a packaged box created on osx. I resolved moving the project dir out of the shared /vagrant folder. I think it's a permission issue of the shared folder on a windows host since I'm unable to see changes made in the windows side from the vm side.

Avatar

The testing question is a valuable one. I am a behavior-driven development addict; Cucumber was the driving force for me to jump ship to Ruby, so I am using Cucumber and RSpec.

I used this railscast as a guide for an app I'm moving to Rails, following the advice to implement auth oneself when new to Rails rather than relying on a gem. Good advice (if sometimes painful!) The sessions controller code worked fine for me with live testing but login tests of bad data generated a missing template error.

Looking at it again, it looked to me as if the create method of the sessions controller code is not asking for the right template when the user enters the wrong info. The error message indicated that it was looking for a sessions/create template, which made sense to me, as the else branch does not have a render statement (and so it defaults to rendering sessions with the method it is in?). To solve the problem, I added render "new" after setting the flash, as in:

ruby
def create
  member = Member.find_by_primary_email(params[:primary_email])
  if member && member.authenticate(params[:password])
    session[:member_id] = member.id
    redirect_to root_url, notice: t('notices.logged_in')
  else
    flash.now.alert = t('errors.invalid_login')
    render "new"
  end
end

Now my sign in features are all passing, yay!

Sorry to be so long-winded, but I'm really new to Rails, so I'm wondering what I got right and what I got wrong in my analysis and solution.

I also wanted to say thank you for RailsCasts. Your service has been invaluable to me as I retool my skills.

Avatar

Very good! I used to overlook asset precompiling.

Avatar

Very good the part about maintenance! I loved heroku's simplicity of such tasks, however I didn't know it was this easy to accomplish about the same thing just with capistrano and a quick Nginx config.

Avatar

Very nice! It would be even nicer if it did something like the miniprofiler showed in episode #368 and display a small expandable box in the corner of your web page with the info about slow queries.

Avatar

Asset precompile can hinder zero downtime too, however it's relatively easy to fix too, if you use nginx:

nginx
  location ~ ^/assets/  {
    gzip_static on;
    try $uri /old$uri;
    expires max;
    add_header  Cache-Control public;
  }

and if you've done generating your public/assets, throw away public/oldassets, and move public/assets to its place!

Avatar

Why would you try to avoid ActiveRecord in migrations when your migration is an ActiveRecord::Migration class?

Avatar

How do assets to work with https and http?

Avatar

Hi,
I am trying to do something different but I can't figure out what's wrong :

I want the user that are using facebook connect to create a password on my website when they first sign up using FB Connect,
So I what I did is let the error when there is no password and instead of redirecting to the new registration form I want them to be redirected to another form (new_facebook) that will let them enter their password, I want the form to be completely different so having another one seems to be the best how can I do that ?

Thanks,

Avatar

Thanks very much for this, Ryan - great timing considering the recent release of Phusion's new premium Passenger Enterprise product, which also allows for rolling restarts. It's good to learn that zero-downtime updates are also doable with 100% open source tools via Unicorn, albeit with increased memory requirements during restart.

Also thanks for including the bit about how to deploy a temporary site maintenance page - a very helpful tip!

Avatar

It heavily depends on how you structure your application, but here's what I'm going to do with my app, where the email is the unique identifier of a user.

First case: the user who registered previously tries to log in via Omniauth which returns the same email. Then the validations that email should be unique fails. You should tell the user that an account with this email already exists, and ask him to enter the password for that account so you can link both (then you don't create a new user, but you add Omniauth's provider/uid to his old account).

Second case: the user tries to log in/sign up normally after registering via Omniauth. In this case he will be told that (log in) the password is incorrect or (sign up) the address is already in use. When this happens you should check to see if the provider attribute of the user with that email address is not-empty, and if so, advise the user to login using "provider" (i.e. Facebook).

Avatar

I'm trying to refresh a kendo chart with new data that uses gon variables as the data......it doesn't refresh the gon variable though with an ajax call! Any suggestions? I looked at gon.watch, but I need to update mutliple variables and it seems to work best with just a single variable and a time interval. I just need to refresh all the gon variables I have on the ajax call.

Avatar

What happens in the following cases?

  • User registers normally, then tries to log in via Omniauth
  • User registers via Omniauth, then tries to log in normally
Avatar

I'm trying to refresh a kendo chart with new data that uses gon variables as the data......it doesn't refresh the gon variable though with an ajax call! Any suggestions? I looked at gon.watch, but I need to update mutliple variables and it seems to work best with just a single variable and a time interval. I just need to refresh all the gon variables I have on the ajax call.

Avatar

Actually, I just ran 'heroku run rake db:migrate' and that's all I needed to get it to work

Avatar

Thanks Fernando - I'm experiencing the same thing. Can you provide some more detail about what you did instead of create_with_omniauth? Thanks!

Avatar

Not Ryan's take, but Gary Bernhardt at Destroy All Software has some great screencasts along those lines.

Avatar

I would really like to see that also.

Btw, don't you guys think that many of these methods could be extracted into a Presenter?

Since they all affect the presentation of the information (they do not modify the data itself), I think would be much better to see it on a Presenter.

The same is not valid to Tag/Category creation, of course.

Thanks!

Avatar

I keep getting "Could not authenticate you from Facebook because "Csrf detected". And can't figure it out... can anyone help?

Avatar

I'm having a problem with the xls.erb file. HTML or XML, when I open it in excel, the file isn't being parsed. I just see all the code, line by line, the way it is in the erb file. However, any of the erb lines, like <% if ... %> statements are correctly interpreted.

I've done the mime type in the initializer as well.

Any help?

Avatar

Looks very promising. Unfortunately, for Postgres users there is an open issue with pg documented here:

https://github.com/mperham/sidekiq/issues/164

and

https://bitbucket.org/ged/ruby-pg/issue/135/segmentation-fault-on-postgresql_adapterrb

Ran into this myself trying to implement sidekiq. Hopefully it will be resolved soon.

Avatar

Thanks a lot Ryan, I was looking for a way to update some existing values in a database and finally I got the answer. Thanks a lot :)

Keep up the good work

Avatar

It looks like you are calling add_evaluation on nil value. You should make sure the variable does not have nil value.

Avatar

Nevermind... I found out my issue was that in the model I was still validating the presence of several fields (including the password).

Avatar

This did not fix my problem :( Do I need to restart my postgre server? Trying now. Will report.

**Back: restarting didn't work, the apt-get thing did that anyway. Rails required version 9.1 (TIMELY--THIS WILL CHANGE. Give rails what it asks for in the error message.). I installed the one listed on the github site (9.0) and it still didn't work. Then, like Mrs. Griswald., I tried sudo apt-get install postgresql-contrib-9.1 instead of sudo apt-get install postgresql-contrib-9.0 and walah, problem solved. Back to the other problem. :)

Avatar

So apparently when ENV is set in the console it's not available to the app.

Any suggestions on a way to set the ENV stuff securely? The code is hosted on Github so having the keys in the source code is a no-no.

Avatar

can you please explain a little more this theme, or make other episode with charts for differents logged in users??

Avatar

If I'm setting the ENV['TWITTER_SECRET'] and ENV['TWITTER_KEY'] variables in the console how can I access them in the views?

Avatar

I use these lines to load my vendor assets into the precompile array dynamically, but your mileage may vary:

ruby
config.assets.precompile += Dir[Rails.root + "vendor/assets/javascripts/*"].map { |path| File.basename(path).slice(/.*\.js/) }
config.assets.precompile += Dir[Rails.root + "vendor/assets/stylesheets/*"].map { |path| File.basename(path).slice(/.*\.css/) }
Avatar

This shouldn't be a problem since a new instance of the controller is generated for every request.

Avatar

Three items to add: twitter bootstrap inline form, non-text fields, reset form

ruby
  <%= search_form_for @search, :html => {:class => "form-inline"} do |f| %>
    <%= f.label :account_name_cont, "Name" %>
    <%= f.text_field :account_name_cont, :class => "input-medium search-field" %>
    <%= f.label :payee_name_cont, "Payee" %>
    <%= f.text_field :payee_name_cont, :class => "input-medium search-field" %>
    <%= f.label :status_eq, "Status" %>
    <%= f.select :status_eq, Bill::STATUS.invert, :include_blank => true, :class => "input-medium search-field" %>
    <%= f.submit "Search", :name => nil, :class => "btn" %>
    <%= f.submit "Clear", :name => nil, :id => :q_reset %>
  <% end %>

with CoffeeScript to handle the reset button:

javascript
$ ->
  $("#q_reset").click ->
    $(".search-field").val('')
Avatar

I was able to get grandchildren to work in the forms with a special application helper function:

ruby
  def special_button_to_add_fields(name, f, association, child_association)
    new_object = f.object.class.reflect_on_association(association).klass.new
    child_object = f.object.class.reflect_on_association(association).klass.reflect_on_association(child_association).klass.new
    new_object.wireless_client = child_object

    fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
      render(association.to_s.singularize + "_fields", :f => builder)
    end
    button_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
  end

Essentially, you have to create the grandchildren in this helper to have an object for the fields_for to attach to.

Avatar

I ended up creating a library to expedite the creation of various fields using Ransack that I obviously think is worth checking out: https://github.com/jbarket/facet_for

Basically, you call f.facet_for :field_name in your search form, and it takes a smart guess, which you can then supplement. It was really created for a large project at work, so the documentation may not be what you'd call extensive... but neither is the documentation for ransack.