RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

There is some magic in the tokenInput code i don't understand. It's closely related to one of the problems I'm having at the moment.

ruby
def author_tokens=(tokens)
    self.author_ids = Author.ids_from_tokens(tokens)
end

seems to create the association between book and authors.

Now the problem. What if I have more attributes on the book_author join table I wish to set before saving the association?
How can I go about this, I'm pretty lost at the moment as I've tried several ways but none works nicely and looks like the Rails way to do it.

PLEASE HELP - any hint would be greately appreciated!

Avatar

Does slug support traditional Chinese character?

here is the code

/app/models/article.rb
class Article < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, use: :slugged
end

Let's say I create an new article with Chinese title.

It seems friendlyId is unable to save the Chinese title in slug column. So the URL still show the id of the article.

If I do this

/app/models/article.rb
class Article < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name
end

It works but I have to ensure no duplicate name.

Any way to solve this?

Avatar

There is a big win when using a ruby based DSL for SQL. For basic queries it doesn't make a huge difference but when building a complex data querying module being able to compose queries out of smaller pieces is very useful.

I built rocket_tag on top of squeel as an example of how to use complex query building techniques in rails.

Avatar

+1 I'm having the same problem of facebook keep adding the #=_. I looked it up and i t seemed like that was intentionally done to indicate that nothing has happened.

@supriya surve, i'm guessing everyone here that's having a problem has already gone through the docs there. I certainly have (read it multiple times), but still can't figure out what the problem is.

Avatar

dude your comments are hilarious, i just looked at your profile

Avatar

I'm answering to my own question: just use the total attribute on the search result:

ruby
@articles = Article.search(params)
@total_articles = @articles.total

Thanks again for the great screencasts !

Avatar

Nevermind, simple mistake. Just had to change get "dashboard/index" to get "dashboard/index" => 'dashboard#index'. I would like to delete my comment but I can't access a delete button.

Avatar

Id love to know as well.. the back button is problematic

Avatar

I have followed all instructions and even copy/paste-d to make sure I made no mistakes. I'm at 6:16, right after adding default_url_options in the application controller and keep getting the same error when restarting the server.

ruby
gems/ruby-1.9.2-p290/gems/actionpack-3.1.3/lib/action_dispatch/routing/mapper.rb:177:in `default_controller_and_action': missing :controller (ArgumentError)

whyyy?

Avatar

Hey all !

I've been struggling for a few days, first installing ES as a service (the 0.19.6.deb wouldn't work on both LMDE and Ubuntu server 12.04), and then displaying results with pagination (I found the ES website quite outdated).

Anyway, I though I should share my small findings:

First for those of you who want to run ES as a service, you should check the service wrapper once you have compiled and installed ES. Then follow the documentation to run it as a non root user

Moreover, my queries didn't return more than 10 results at a time. I fixed this adding a match_all:{} parameter in the tire.search function :

ruby
def self.search(params)
  tire.search(load: true, match_all: {}, ... ) do
  # ...
end

I also have a question: how can I retrieve the number of hits return by query when using pagination?

Thanks again Ryan for your amazing screencasts !

Update: the newly released version 0.19.7 of the deb package fix the installation issue

Avatar

Seems there's something wrong with the coffee indent. I'm new to this. What's wrong with it?

Avatar

Hi, I followed the tutorial step by step

but my remove function won't work.

add function work fine, remove using checkbox works fine. Why?

Avatar

I'm using Omniauth to authenticate at Twitter, but I have 2 apps registred with diferent names that I want to use depeding on the current locale(session scope).

So I need to change the provider key and secret defined at omniauth.rb file right before user calls auth/twitter( I was thinking to do a before_filter but auth/twitter is an external link to twitter and not a regular action) or a way to config Omniauth to define providers by locale instead of define for the entire application scope.

So how can I do that ? Any idea?

Avatar

Very useful, just been looking for this! Thank you.

Avatar

If you are on linux or mac, then you can put it a file called /home/.bashrc

  • cd $HOME
  • vi .bashrc
  • then add your variable near the bottom like so:
ruby
export NAME_OF_VARIABLE=xyz123

Tip: Use your real variable name, there's usually no need for quotation marks, and the export keyword is required as shown above. Finally, you should make sure your variable name is written in UPPER_CASE.

Remember to save and close the file, before reloading your command prompt.

Avatar

It's just a sample, not a full solution. If you built and deployed word for word in this demo, then that's foolish.

Avatar

Is there an elegant way to deal with optionally-passed locals?

For example say I call

ruby
<%= render 'posts/post', post: post, :size => :panel %>

How can I access that size value in the presenter?

One way is to pass the value into the presenter. For example, from the partial, I might write

ruby
<%= post_presenter.some_method(size) %>

But since size is an optional value passed to the partial, it might not exist, and thus would raise an exception when trying to call some_method. You could check if the local variable exists like this:

ruby
<% if defined?(size) %>
  post_presenter.some_method(size)
<% else %>
  # Don't call presenter method at all, or do other logic.
<% end %>

However, this is ugly, and defeats the point of the presenter! This is the code that we're trying to avoid in the first place.

Thoughts?

Avatar

The second version is actually what worked for me on OS X. The Article.search method threw an error while trying to access @search.results

Avatar

Where do you set the ENV variable ?

Avatar

You may need to set the following in your environments/tests.rb file to avoid problems down the track:

test.rb
config.cache_classes = !(ENV['DRB'] == 'true')

For some reason caching seemed to randomly kick in for one of my models while I was testing it and after that none of my changes to the model had any affect. I'm not the only one to have experienced this:
http://www.avenue80.com/tiny-tip-spork-not-reloading-classes/#comment-133

Perhaps I did something wrong, but I don't think so and changing that line fixed the problem.

Avatar

Has anyone gotten the TokenInput to work with Nested Forms from his revised #196 episode? (http://railscasts.com/episodes/196-nested-model-form-revised)

Avatar

Bootstrap is a game changer for sure. Any chance we could get a quick update on how to use it along with tools like http://bootswatch.com/ or https://wrapbootstrap.com/ to introduce some variation into our designs?

Avatar

I ve got the solution, what do you think about that

application.html.erb

ruby
<!DOCTYPE html>
<html>
  <head>
    <title>Cinematron</title>
    <%= stylesheet_link_tag    "application", media: "all" %>
        <% if current_user %>
        <script>
                at = '<%=current_user.oauth_token%>'
        </script>
        <% else %>
        <script>
                at = ''
        </script>
        <% end %>
....

facebook.js.coffee.erb

ruby
  if $('#sign_out').length > 0
    FB.getLoginStatus (response) ->
      if ((!response.authResponse) ||((at != response.authResponse.accessToken)))
        FB.login (response) ->
          window.location = '/auth/facebook/callback' if response.authResponse
        , scope: "email,publish_stream"

In this way when auth token is expired but user is connected you have an automatic relogin client side.

Curious for your opinion
Bye
Nunzio

Avatar

anyone know if its possible to override CSS based on a subdomian?

Avatar

I use ColorPicker in Sublime Text 2. It's available in Package control for an easy install. I click on the color and hit Ctrl+Shift+C to bring up the color picker, and when I hit ok, it types out the color chosen.

Avatar

The best way to do it is to use a decorator as Ryan has done with the authenticate method. To wit:

ruby
Refinery::PagesController.class_eval_do
  before_filter :find_pianos, :only => [:home]

  def find_pianos
    @pianos = ::Refinery::Pianos::Piano.all
  end
  private :find_pianos
end
Avatar

what do you think about an aproach like this?

if $('#sign_out').length > 0
FB.getLoginStatus (response) ->
if !response.authResponse
FB.login (response) ->
window.location = '/auth/facebook/callback' if response.authResponse
, scope: "email,publish_stream"

Avatar

Great episode
When last month fb revoked the offline-access token perms, I had several rework in my apps.

In which way do you managed this?
https://developers.facebook.com/roadmap/offline-access-removal/
Somebody has an example?
In next railscasts you will cover this?
The problem is, I want to post something in user wall while he uses my app throught a mobile api, for example. If the accesstoken user stored when he logged first time expire, how did you manage this case?
(sorry for my terrible english)
Nunzio

Avatar

Hi Ryan,
This code last_email.to.should include(user.email) would check that last email was sent to the specified email. But how would you ensure that Password reset email was sent not any other email?

Avatar

Quick question, I notice that the facebook sign-in popup uses SSL, but the app you create does not. Would you recommend adding SSL everywhere, in order to stop session attacks? Heroku charge a whopping $20 per month to enable SSL endpoints.

Avatar

This is great! Could you possible revise integrating omniauth with devise? I'm using omniauth-facebook and devise and I have a couple weird issues. One of which is when a user first registers for my site devise won't autolog them in even though I used signin_and_redirect. The other problem is facebook keeps adding #=_ to my url after I login.

Avatar

The error is due to a violation of the same-site origin policy caused by the AJAX calling to a script on another domain. It would be better to use jQuery or raw Javascript to append a new script element to the head and allow the browser to interpret it as a static asset.

javascript
(function(d){
   var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
   if (d.getElementById(id)) {return;}
   js = d.createElement('script'); js.id = id; js.async = true;
   js.src = "//connect.facebook.net/en_US/all.js";
   ref.parentNode.insertBefore(js, ref);
 }(document));
Avatar

Turns out it was just an indent issue. Dope.

Avatar

Hi Ryan. I swear I had this working....maybe this is a rails 3.2.3 problem. Im getting a "undefined local variable or method" error on my form action. Everything is set up following your directions.

<%= form_tag require_certificatendorsements_path, :method => :put do %>

Any ideas?

Avatar

Hi Ryan,

Did you try to set this header from your app in order to prevent the javascript error?

ruby
response.headers["Access-Control-Allow-Origin: facebook.com"]

Don't have time to try it right now, I can try it tomorrow maybe.

Greetz

Benoist

Avatar

I just tried both out of curiosity;

When I use "errors[:base] << message" it returns:
- errors
- errors
- errors
- errors

When I use "errors.add :base, message" it returns the exact validation errors:
- First name cannot be empty
- Last name cannot be empty
- Number is required
- Verification value is required"

So I ended up using: errors.add :base, message

Avatar

How do I implement using coffeescript?
Please show examples of the new rails 3.2.X more Highcharts
We are curious to know how the new version of rails.

Thank you.

Avatar

I think i got it working but i'm trying to use a table rather than a ul/li and it doesn't seem to be passing the right thing to the sort action. no matter what, it passes the original order even after dragging+dropping to reorder the list. is there a way to get tables to work with this?

Avatar

figured it out with

:dependent => :destroy

Avatar

Wow, this is really great! Very nice screencast, Ryan; it's neat to see how easily it can be done!

A little OT, but I was amazed at the number of columns and amount of data in the User table. They pretty much keep everything there...At first I thought that would be a tremendous amount of overhead to get that much data every time you want to query a simple user attribute...?

But, on second thought, they probably store the entire User table in some gigantic memory cache.

Anyway, neat stuff!