RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

I wanted to use multiple providers for 1 account, so I can sign in to the same account using Facebook or LinkedIn.
When e-mails from providers match, I add them to the existing user.

I changed:

/app/controllers/authentications_controller.rb
user = User.new

to:

/app/controllers/authentications_controller.rb
user = User.find_or_create_by_email(omniauth['info']['email'])

Without this change, I was redirected to the new signup form while adding a second provider. And because my e-mail was already in use, there was no way to add both Facebook and LinkedIn

Avatar

Hello Luke and Elliot,

Do you have any pointers as to how to set Devise authentication on an existing rails app with backbone.js?

Thank you!

Avatar

I'm using the gem nested_form - it's great! But there's a (beginner) problem I have with its output. The fields_for

ruby
<%= f.fields_for :news_item do |report| %>
...
<% end %>

seems to wrap everything in it in a <div class="fields">...</div>. How to avoid this?

Avatar

Does anyone have any tips for making this work with domains instead of subdomains? I'd like to have the tenants set up so that it's grabbing the tenant from the actual domain name. Then I can mask the domain, so that multiple domains are using the application, and depending on which domain they are using, they will have a different schema.
Thanks,
--Mark

Avatar

Hi Ryan --

I was working out a different problem and wanted to get to a known starting point, so ended up at this episode, which you have since revised. The code here doesn't work in a default Rails 3.2 environment for a couple of reasons which are resolved in the revised version.

I wonder if you might want to add a feature to your site, that provides a notification when an episode has been revised with a link to the new one? Or perhaps if you haven't yet revised an episode just a note. For example, before the revision, this one might have a note like "As of Rails 3.2 the code in this example does not work. See comments for solutions."

I have been using Rails since 2007, and it's a testament to your understanding of how all of us actually learn to code that you have picked topics that live for years!

You rock!

Tom

Avatar

This Railscast should prob. be updated to use the Flex gem.

It's a great great gem because it has model mapping & scopes like AR does.

Avatar

I am also interested in these two cases and the solutions proposed be David would work for me. I have tried a few approaches but, like Dan, have run into issues. If anyone has a code example for this it would be great.

Thanks

John

Avatar

Are you still looking on how to do this?

Avatar

which is best gem for uploading video

Avatar

Aditya, as I understand it, when a web request comes in to a running web server, it will be handed off by Passenger (or whatever you use) to a running ruby process that has already handled a prior web request. Since the prior request most likely had a workflow that ran the before filter, and since the before filter sets the time zone for the entire process, that time zone is now being used for any code running in that process. If that is not undone when the request is done being responded to, then the next incoming request to that process will see all times be displayed in that prior zone. This is of course avoided if the before filter sets the time zone for every single incoming request, but it's safer (although probably slower) to use the around filter, in case you have any current or future case where the before filter might not be run for some reason.

Avatar

For those using Bootstrap, note that the preview won't work correctly until you disable bootstrap's default CSS of img { max-width: 100% } by specifying img { max-width: none ).
See here.
https://github.com/twitter/bootstrap/issues/1649

Avatar

I used code as described in this episode:

ruby
ser.facebook.put_connections("me", "my_apps_namespace:recommend", event: event_url)

It works fine in sandbox mode, however when trying to submit for approval I get the following:

our code is currently configured to publish a stream story. You must change your code so that when the test user triggers the action it produces an open graph story. Please make the appropriate changes and resubmit.

Had anyone else experienced anything like that?

Avatar

I've never had an issue using before_filter when setting time zone. Its local.

Avatar

The feeds only show the free ones. Everything since Turbolinks has been revised or pro.

Avatar

Is anyone else having issues where they can only get the search functionality to work within the index action only?

Avatar

Great screencast series. This is exactly what I'm looking for. Sadly it doesn't work for Rails 3.2. Helper method's seem to have changed in Rails 3. Any tips?

Avatar

Is the Atom feed broken, or am I missing something?

I haven't received any updates in google Reader since Turbolinks. Looking at the XML at http://feeds.feedburner.com/railscasts, it hasn't been updated since then either.

Avatar

How would you use this authorisation logic with Devise?

I tried:

module Permissions
  class GuestPermission < BasePermission
    def initialize
      allow :devise_sessions, [:new, :create, :destroy]
      allow :sessions, [:new, :create, :destroy]
      allow :user_sessions, [:new, :create, :destroy]
    end
  end
end

But a guest is never able to login :(

Avatar

Thanks for clearing it! I didn't notice that matchers behavior differs from query methods behavior.

Avatar

I do something similar. You may find the constantinople gem useful.

  1. Put all your non-secret config settings (eg - hostname), as well as "dummy" secrets into a config/app.yml.default file that you store in source control.

  2. Gitignore config/app.yml.

  3. In production, use chef templates to generate config/app.yml. Devs can also maintain their own local over-rides there as well.

If you prefer, instead of keeping config/app.yml.default and overriding with gitignore'd config/app.yml... you can keep config/app.yml in source control, and override with a gitignore'd config/app.yml.override

Avatar

ok seems it got lost in 3.x ;) sorry for bothering

Avatar

To quote the capybara README you linked: "Capybara's Rspec matchers, however, are smart enough to handle either form." That means that should have_no_content and should_not have_content are functionally equivalent.

But thanks for pointing that out, I didn't even know there was a difference.

Avatar

http://blog.envylabs.com/post/29045466981/the-rails-state-machine

probably this would be nice too in the show notes.

it seems to me that not very much people know about the built-in version.

just used it once. i dont even know if its also built-in in the current version of rails

Avatar

So after some time on google I bump into this. Am trying it, it saves to postgresql DB.

http://www.rubydoc.info/gems/carrierwave-postgresql/frames

Will update once I get it working fine.

Avatar

Has anybody got the tokeninput example working with Postgres? I've tried substituting the like for ilike and ILIKE but it doesn't seem to work, in the console the q is registering but the query itself remains blank, %%. Any help would be appreciated.

Avatar

I am using this gen with active admin. I want to be able to save the file/image to a postgres DB ... the data types in the DB are all set as bytea.

How can I achieve this?

Avatar

@brucepom: Add rel="nofollow" to the pagination links, so Google will not index the paginated list. In addition, add a sitemap.xml to your site to tell Google the single pages.

Avatar

I'm placing a comment onto this episode as it seems the most relevant.
Has anyone done a good example on the use of rails has_and_belongs_to_many, as i cannot think of a scenario in which i do not use has_many through: and i just cannot get my head around the habtm function...

Avatar

Hey Kevin, did you ever figure out a way to integrate cancan with Sunspot?

Avatar

Any thought on how to do this in a multi tenant environment? Ideally something that would filter the search results by the current tenant.

Avatar

Thanks Ryan. Good review.

What bothers me about most of these is that they keep state behavior all in one class.
That can make for a big state model class.

An alternative is something like StateObjects
which uses the State Design Pattern from the Gang of Four book. The state behavior is moved to small separate classes. StateObjects has less support for transitions/events but more for extracting the behavior.

Avatar

What is the best way to test using Test Unit?

Should I test it in my functional test or create a unit test?

Avatar

is this working for you ? if I set it to listen on 9292, it crashes right after start.

Whem im using it on its defaults - port 3000, and approach explained here in this railscast, it works perfectly using curl, but when I try to make Net::HTTP request in broadcast method, it fails on timeout.

Any ideas how to make it work?

Avatar

I have an issue where the form is sending nil when it has found a match for the query.

anyone know what up wit dat?

My needs are a little different than the video. I want a field where I can put in the name of a book. It does the index jason search and has a tokenLimit of 1. If the book is not found - it makes a new book. If the book is found I want the controller to direct me to the book that already exists show page. For some reason right now if the book is found it sends an empty name parameter to the controller and I cant figure out why.

Avatar

When you add resize_to_limit(600, 600) to the crop method to solve the problem that the x,y,width,height are relative to the :large image, it seems like you potentially lose some resolution.

It certainly makes sense to scale the image down to something reasonable before displaying it in the cropping UI, but if you're using this to generate a new image that's bigger than a thumbnail, it would be really nice to be cropping from the big image, not the 600x600 one. Seems like it would be better to scale the x, y, width and height values to work with the original image rather than scale the image.

What would be the most efficient way to get the dimensions of the original image in the crop method so that one could scale the values instead of scaling the image?

Avatar

I created a migration to add a position:integer field, used a hidden_field inside partial with :class => 'position' and included this line of js before event.preventDefault() to the .add_fields event:
> $(this).prev().find('.position').val(time)

and on has_many association, i used

has_many :posts, :order => "position"

Avatar

Excellent episode Ryan. The community really appreciates your tireless efforts.

Avatar

Hello,

I am fresher with ROR so i am trying to crop a picture but i get this error in cropping how to solve this help me?

Can't mass-assign protected attributes: crop_x, crop_y, crop_w, crop_h

Avatar

no, these crop coordinates are not saved anywhere

attributes you define as attr_accessor are only available to you temporarily for a particular instance of the record, if you want to use it for future, you will have to save them in database yourself :)

Avatar

One thing that caused me some consternation: a misnamed keyfile.

When you create the keypair at Amazon, the name listed on amazon must match the filename locally.

Also, Ryan removes the .pem extension, from gsg-keypair...and Rubber does not tack .pem onto what you define in rubbery.yml.

So in short, make sure the key files names match everywhere.

Avatar

In the earlier part of the episode, Ryan used a cattr_accessor which is a Rails shortcut for creating class methods.

(I think this is right, but anyone who knows better, please correct!) The reason to consider thread safety is that unlike instance variables, class methods are considered "static". Depending on how you have Rails deployed in a production environment this is not inherently thread-safe -- Ryan did a recent RailsCast on thread safety that explains more, but the short answer is whether or not something will be thread-safe depends on an external configuration that might change with a new version, or work differently in a few months, etc.

For me, at least, that's reason enough to add this little bit of safety.

I don't have a solid answer on the use of the instance variable, but I think it boils down to this: is @tenant_id that you reference at one moment necessarily the one you reference at another, or is it one on another thread? Again, the fact that this is a class method, not an instance method is what makes the difference.

(And if my explanation is wrong, I do hope someone can correct me so we all understand :-)

Avatar

Devise is putting new users in the public schema. Will your code fix this? Where does the code go?
Thank you.

Avatar

It's not really all that different than what Ryan shows in this episode, or perhaps not at all -- there's something in the request that identifies which tenant is current (the current_tenant method, for example), and there's some sort of table that contains details about the tenant.

You can decide how you want to set up your web server -- you might set up a virtual host for each domain, or in the case of a small number, a single vhost that handles all domains (e.g. using Apache's ServerAlias directive). While it's also possible to let all requests through on the default host (sometimes called the "catch all host") and handle the ones you know, I prefer having a more declarative setup.

I also recommend having some sort of immutable unique text key (all lowercase, single word) that you use to identify the tenant in the database. Once you do that, you can use it as a kind of namespace that allows your app to pick up tenant-specific CSS selectors, locations for assets like logos, and so on.

Avatar

PostgreSQL schemas are a great thing, but I completely agree with Martin -- whether you have multiple databases, or a single database with schema namespaces, you're only solving one part of the problem -- the application still needs to be aware of multi-tenancy.

For example, the Admin back-end of an app I just finished usually needed to see information across tenants. Further, we wanted admins to be able to log in to our tenants' sites with their normal username (that had a role whose permissions allowed this).

And you're creating a larger problem managing the system, etc., and again, while PostgreSQL is (IMHO) by far the best RDBMS out there, why tie yourself to a specific database feature unless you really have to?

The bottom line is that building a multi-tenant app is an up-front design decision that needs to be baked in at many levels. It's harder to write, test, and so on, but that's just because it's a hard problem. Not impossible, just harder. This is most definitely not something I would suggest most apps farm out to a gem -- it's never that simple.

Tom

Avatar

Agree! And one other point we learned the hard way: we had used subdomains for environments for testing and staging (e.g. tenant1.staging.example.com) and didn't realized until too late that wildcard domains only give you one level of subdomain. A better strategy is to do something like tenant1-staging.example.com.

Avatar
Solution
  def self.authenticate(email, password)
    find_by_email(email).try(:authenticate, password)
  end