RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

RABL does support caching in Rails.

https://github.com/nesquena/rabl/wiki/Caching-in-RABL

I'm new to RABL so I haven't tried out the caching yet.
Looks pretty simple ... does it not work?

So far I have really liked RABL and for me I like the view approach better.

Avatar

It's a matter of tradeoffs and deciding what's important to you. I tend to check my VCR cassettes into source control, because I like having the history of what the HTTP responses were at a particular point in time. It allows me to git bisect through my history and having passing tests. If the cassettes are not committed to source control, and the HTTP responses have changed, you'll have a very hard time running the tests at an old commit.

However, committing the cassettes does tend to bloat your git repository with lots of extra files, and it makes it easy to wind up with tests that require particular exact cassettes (e.g. because you hand-edited them) to pass. I like that not committing cassettes encourages you to just treat them as a cache.

It's up to you ultimately -- just consider what is more important to you of the pros/cons I've listed here.

Avatar

I'm getting the same error when I try it. I just watched the video, and ran through the tutorial, so developer error may be the cause, but if you find a solution before I do...please post.

Avatar

One improvement I made was implementing an includes call and setting it to an instance variable so I can reuse the nested relationships without having to re-query the model every time:

def author_name
  posts_with_children.map do |post|
    post.comments.map do |comment|
      comment.author.name
    end
  end.join(',')
end

private
  def posts_with_children
    @children ||= posts(:include  => { :comments => { :include => :author } })
  end

This improved performance slightly, but not a significant amount. Right now I have an initial page load of 5 seconds, but that is only with 4k records. If anyone has any other advice on how to improve this further that would be great. Thanks.

Avatar

I am having some performance issues with deeply nested models. I have a parent Topic model. A topic has many posts, posts has many comments, and a comment has an author.

mapping do
  indexes :author_name, index: 'not_analyzed'
end

def author_name
  posts.map do |post|
    post.comments.map do |comment|
      comment.author.name
    end
  end.join(',')
end

Any tips on optimizing the performance?

Avatar

If you are receiving an error message similar to

An unexpected error has occurred. We have been notified of the problem.

then this could be due to the fact that you have updated your API. I have a support ticket into Stripe to see what can be done about this. However, currently, I've just bypassed this error using the below coffeescript.

coffeescript --yum
      if response.error.message == "An unexpected error has occurred. We have been notified of the problem."
        $('input[type=submit]').attr('disabled', false)
      else
        $('#stripe_error').text(response.error.message)
        $('input[type=submit]').attr('disabled', false)
Avatar

aaaaand it's broken

bash
vagrant@lucid32:/vagrant$ bundle exec unicorn -c config/unicorn.rb -D -d
{:unicorn_options=>{:listeners=>[], :config_file=>"config/unicorn.rb"},
 :app=>
  #<Proc:0xa15f748@/home/vagrant/.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/unicorn-4.6.2/lib/unicorn.rb:39 (lambda)>,
 :daemonize=>true}
Exception `EOFError' at /home/vagrant/.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/unicorn-4.6.2/lib/unicorn/launcher.rb:46 - end of file reached
master failed to start, check stderr log for details

Does anyone have any ideas?

Avatar

I have been writing backbonejs apps on top of rails for two years. The first company I worked for used JBuilder, and the company I work for now uses RABL. Both are neat, but I have yet to find an easy way to do caching with them. Last year I stumbled on this article http://www.broadcastingadam.com/2012/07/advanced_caching_part_6-fast_json_apis/ and now all of my personal projects are ActiveModel::Serializers. Super easy way to cache json responses.

Avatar

It seems that I should prebuild :fields in controller:
def new
@product_type = ProductType.new
@product_type.fields.build
...
end
or it won't show.

Avatar

I agree. It seems simpler and cleaner to stick with RABL since it's just another view type. Sticking with a view layer, whether viewed by a browser or "viewed" by an API, is just more intuitive to me. Plus, passing around a project built with RABL is going to be a lot easier to understand by a random 3rd party.

Maybe, like you said, this is better for knocking something out quickly or if it's a small project you work on alone. It's going to get really hackey feeling after 5+ controllers each running their own tests...

Avatar

Did you ever get a fix for this?

Avatar

I don't see the point when i would ever use this over RABL or Jbuilder. It looks to me like a way if you need to hack out something quickly but when it gets more complex would switch to one of the both mentioned above.

Avatar

Rails can be used as more than a full application framework but also to serve JSON apis to be consumed by different "views" that might not be even in the same app.

These other different "views" could be other Rails apps, Clientside javascript frameworks within your own app, iOS/Android apps, etc.

To consume APIs from your Rails app you would use something like ActiveResource http://railscasts.com/episodes/94-activeresource-basics, https://github.com/rails/activeresource

Avatar

as a example u can watch previous cast about ember, frameworks such as ember use json as data source.

other example is building API interface, as a real example you look at shopify.com api interface, its provided by json

Avatar

Ok, so after watching this screencast I have two questions.

  1. Why doesn't Ryan ever seem to use the respond_to syntax he covered way back in Episode 224

  2. All the Railscasts episodes I have seen that cover Json always focus on customizing a response, but as a person still learning, I have never figured out what to do with a Json response. I also can't seem to find any good example apps that cover this. So now I know at least three ways to generate a Json response and still no idea of how to "consume" that response on the other end. This might be completely obvious to an experienced programmer, but not to me.

Avatar

if you use the helpers like content_tag and use :data => { :articles => @articles }

they will be automatically converted to json and escaped correctly

Avatar

Hi Ryan,

Thanks for this tutorial. I certainly prefer Active Model Serializers to RABL or Jbuilder. I also like the default rails' as_json method.

I have a comment regarding that. You have mentioned in several tutorials, that "we can get some basic json api by overriding the as_json method".

While this is true, it's also not recommended. Overriding as_json has a very well known downside: it doesn't respect the overriden as_json method in included structures. For example:

  • Let's say that Article has_many :comments.
  • You override as_json in Comment and Article. On the latter, you add a :include => :comments clause.
  • When you do render :json => @article in your controller, the article will include the comments, but they will not have the format that you specified in Comment#as_json. Instead, they will come with the "Rails default format".

The reason this happens is because of the way Rails is built internally. In some edge cases, reading the structure provided by as_json would provoke infinite loops.

The recommended way to solve this issue is using an external lib, like the ones you mentioned. But if you don't want to, or can't do it, then your next best thing is to overriding serializable_hash instead of as_json. Both methods work very similarly, serializable_hash just happens before in the call stack. Usually replacing def as_json by def serializable_hash in all models is enough to fix the nested dependencies issue.

Avatar

Sorry, we can use .reset_counters:
Category.all.map(&:id).each { |id| Category.reset_counters(id, :products) }

Avatar

Specifying a counter cache will add it to that model’s list of readonly attributes using attr_readonly.

I think raw SQL within migration is the only option to update counter cache column.

Avatar

Just wondering if anyone has tried to use this in Rails 4.

Avatar

This is exactly the main difference in choosing Ember over Angular or Backbone. When you get into large applications like im working on, Angular and BB both become more difficult to manage. Zombie memory from events and views becomes a manual problem. Angulars dirty checking becomes more of a problem with large apps. And Nested views is a PIA compared to Ember. I find that for small apps Angular is probably a better choice. But if you are building a large web app Ember becomes the much better choice.

http://jsperf.com/angular-vs-knockout-vs-ember/99

I also find it kind of sad that there seems to be this love hate thing with JS frameworks. I think there are great things in both and, depending on the job, either could be a best choice.

Thanks again Ryan for the great stuff!

Avatar

Have you found a solution. I'm struggling.

Avatar

Hi,
How do I redirect www subdomain to another webapp?

Thanks!

Avatar

If u want email confirmation when users sign up, add the option confirmable in the model User.rb. also in the migration uncomment the lines corresponding to confirmable.
Add the lines
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:enable_starttls_auto => true,
:address => "smtp.gmail.com",
:port => 587,
:domain => "mydomain.com",
:authentication => :login,
:user_name => "myemaiL@mydomain.com",
:password => "mypass"
}
to config/environments/development.rb

Avatar

Ok, the jQuery selector in the javascript to prevent ajax from sending a request to the server for the pagination links which have an href='#' is...

ruby
$('#products th a, #products .pagination a[href][href!="#"]').live('click',

This prevents attaching a click event to pagination links where href='#'.

Avatar

The javascript to handle the pagination link clicks sends the ajax for even the pagination links that are disabled. Even though their href is "#". Is there a way to filter out the live() call to not include the items in the pagination links which have a class of 'disabled' or 'active'?

Avatar

Thanks for reporting this mistake, I have corrected the text in the ASCIIcast

Avatar

Thank you Ryan! Good RailsCast as always.

Avatar

I found that in Rails 4, setting name: in f.file_field didn't work: Rails appended [] to the end of the field name regardless. I had to replace this:

    <%= f.file_field :image, multiple: true, name: "painting[image]" %>

with plain HTML, like this:

    <input id="painting_image" multiple="multiple" name="painting[image]" type="file" />
Avatar

yeah, figured that out! thanks for great work :)

Avatar

Thanks for mentioning this, been looking for a HAML-like engine for JS - it does look great.

Avatar

Did you spend the same two weeks learning AngularJS? Makes sense that if you spend two weeks on something then it will start to make perfect sense. It's just because you are learning it. ;-)

Avatar

RABL works well with versioncake and it allows you to avoid duplicating your controller logic-it's mentioned in the related library section: https://github.com/nesquena/rabl#related-libraries

https://github.com/bwillis/versioncake

Avatar

Why do I keep getting the error

An error has occurred
Client authentication failed due to unknown client, no client authentication included, or unsupported authentication method.

when trying to sign in through the client app?
I tried running the source code and I get the same errors... any ideas?!

Avatar

Hey Everyone,

I'm new to ruby on rails so forgive me. How does active admin know where your products are and how does it pull them in? I see after you setup active admin the products were already in there.

Thanks!

Avatar

ember-auth is a gem that's building towards that - looks like they've gone a good way.
Includes a demo project on github, a tutorial, and accompanying working demo site on heroku.

Avatar

I would love to see something too...

Avatar

You only need to do the secure cookie thing if you don't want to process all request over https

Avatar

Exactly! I've faced a problem that ember-data simply don't handle nested resources - there is no way to hit /people/:person_id/something, it will be a /people_something for now.
So, it doesn't matter how mature Ember is, it will be just a local toy until ember-data conforms to its level, imho.

Avatar

From my little research of angular I would agree, I can see using it here and there sort of thing. But ember has the potential to change how web apps are built moving forward, the way rails did 10 years ago... At least I think that's the ambition. Will depend in large part on the success or failure of ember-data which is still a work in progress. We shall see.

Avatar

great episode and I've got it (except I used carrierwave in the background to download from S3 and process it)

One small thing though: if the images have the same filename, (like if uploaded via iphone's mobile safari'), somehow the files end up being duplicates, instead of showing 2 different files. Has anyone had that issue?

Avatar

File is corrupted. "General input/output" error.
I am using liber-office on Debian Ubuntu 12.04. Dont know why its corrupted.

Avatar

Same for me. File is corrupted. "General input/output" error.
I am using liber-office on Debian Ubuntu 12.04. Dont know why its corrupted.