RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

Yet another set of conventions that will help simplify Rails apps. I love it. I know a lot of people were disappointed that Rails 2.0 wasn't going to add any "big" features, but it's good to see that the focus has been on further simplifying the code that's written for the most common cases.

Avatar

Seem I am out of date here...So no more rhtml? .html.erb now?

Avatar

It seems to me that this is meta just for the sake of being meta. Maybe that's just something you wanted to show in the screencast, but this seems like a cleaner way to do it:

%w{company privacy license}.each do |a|
  map.send "about_#{a}", "about/#{a}", :controller => 'about', :action => a
end

Avatar

Joel, I don't think the problem is a namespace. Jamal probably made a ProductController instead of a ProductsController.

Jamal, always remember to pluralize your RESTful controllers:

script/generate controller products

Avatar

If you use the namespace route like that :

map.namespace :admin do |admin|
    admin.resources :products
end

you can write this :

<% form_for([:admin,@product]) do |f| %>

Avatar

When I type

<!-- index.html.erb -->
<%= render :partial => @products %>

Then it search for partial in the wrong folder?

/products/_product

and not

/product/_product

Avatar

Thanks a lot for this Ryan.

+1 for a separate validations screencast!

Avatar

Thank you so much for putting this together. It was incredibly helpful! Please add my vote to your doing a part 4 on validation.

Avatar

In your code you point the form url at project_path, where is that set and is there a Railscast about what it is etc?

Great stuff though, this is exactly what I need to do :) Thanks

Avatar

You won't see much of a performance problem re-loading each time. Especially in rather simple model's like the one in the video.

Many people store session data in the database nowadays, a good practice, so even if you do store it in the session, you're not saving yourself a round trip to the DB.

I recommend the approach Ryan so eloquently explained.

Avatar

Thank you so much for your great screencasts! Very inspiring and informative and quite entertaining as well:-)

I ran into problems with the encoding of German Umlaute characters, such as "äöüÄÖUß" with PDF::Writer.

I have my source code encoded in UTF-8 and PDF::Writer cannot yet display UTF-8 characters.

A great solution is to overwrite PDF::Writer's text method and have it convert the text from UTF-8 to ISO-8859-15, like so:

CONVERTER = Iconv.new( 'ISO-8859-15//IGNORE//TRANSLIT', 'utf-8')
module PDF
    class Writer
        alias_method :old_text, :text

        def text(textto, options = {})
            old_text(CONVERTER.iconv(textto), options)
        end
    end
end

All credits go to Peter Krantz and Anibal. See http://www.peterkrantz.com/2007/utf8-in-pdf-writer/

Avatar

Ryan, many thanks for every single episode. It's fantastic how you show the world of ruby, rails and the whole thing interact together. :-)

Keep your good work, thanks again!

Avatar

@lester - He said "dig around"! He has referred to "digging" in the past, so I am sure he is not a potty mouth. You have got your mind in the gutter! ;)

Avatar

I have an Items model and a Categories model. Item belongs_to Category and Category has_many Items.

I would like to filter Items by Category. As I understand it, it would have to be something like '...items/filter/[cat_id]'.

modifying the routes file like this:

map.resources :items, :member => {:filter => :get}

Here is my first question, I am filtering Items by category_id, I feel I need to use :collection but then I would not be able to use an id. Am I doing something I am not supposed to?

Also, instead of getting the reoute I want when using filter_items_path I am getting: .../items/[category_id]/filter

Appreciate if you could help.

Avatar

@Andres: I think that you have to edit the routes.rb file in the config folder so that it has:

map.resources :project

in it... but I'm not 100% on that, because I'm still getting an error.

Avatar

This is awesome.... but it's not working for me. When you said use "restful routes" discussed in earlier railscasts, you meant map.resources, right? I added that, but now I get an error. I can show more if this isn't enough. And yes, "aoifna" is always what I use to test form inputs. Thanks for the railscasts. I use them often

Here's the error:

NameError in MoviesController#index

uninitialized constant MoviesController

RAILS_ROOT: script/../config/..

Request

Parameters: {"search"=>"aofina"}

Show session dump

---
flash: !map:ActionController::Flash::FlashHash {}

Response
Headers: {"cookie"=>[], "Cache-Control"=>"no-cache"}

Avatar

For Rails 2.0 you need to do like this in your config:

ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS[:due_on] = '%m-%d-%y'

:)

Avatar

This appears to be broken in Rails 2.0 :*(

Avatar

I'm having the same problem as Paul, is there an easy solution anywhere?

Avatar

did you say "dick around" near the end there? ryan, i'm shocked! :)

Avatar

Thanks for another great screencast. I have been working in the 2.0 preview version of rails and have found some modifications are needed to make it all work with the equally awesome now form authentication system.

I added an additional parameter to the function that passes the authentication_token. This is used to create a hidden field appropriately named for the auto-authentication:

function confirm_destroy(element, action, message, auth_token ) {
  if (confirm(message)) {
    var f = document.createElement('form');
    f.style.display = 'none';
    element.parentNode.appendChild(f);
    f.method = 'POST';
    f.action = action;
    
    var m = document.createElement('input');
    m.setAttribute('type', 'hidden');
    m.setAttribute('name', '_method');
    m.setAttribute('value', 'delete');
    f.appendChild(m);
    
    var t = document.createElement('input');
    t.setAttribute('type', 'hidden');
    t.setAttribute('name', 'authenticity_token');
    t.setAttribute('value', auth_token);
    f.appendChild(t);
    
    f.submit();
  }
  return false;
}

Avatar

Don't forget Wirble!

It's my favorite console trick.

Avatar

Whoops! Should have tested that before posting... Now when a user signs up, they could send a post request with anything in the indentity_url field and not have to put in a password.

Avatar

Instead of passing false to the save method, I just modified the password_required? method in the user model.

It now reads:
(crypted_password.blank? && identity_url.blank?) || !password.blank?

Is doing something like that ok?

Avatar

Hi Ryan,

Thanks, your screencasts, just great as always!

I wonder why you use the ProductDrawer class in lib. Why don't you use a method in the Product Model?

Avatar

Hi! It,s possible to send two or more parameters in RESTful action? For example
some_action_path(@news, @comment) ??
Btw. Great screencast!

Avatar

@Nik:
your are so kind~
that's cool~
thx~

Avatar

Great stuff. Am interested to know what the prompt is for rails also [FILTERING] out the password confirmation field? Is this parameter key a regex?

It's suggested here that you need to have both :password and :password_confirmation in the filter_parameter_logging call -

http://wiki.rubyonrails.org/rails/pages/HowtoAuthenticate

Avatar

Brian: If worst comes to worst, you can have a catch-all route and do logic in a controller: http://railscasts.com/episodes/46

A very interesting, but pretty ugly/hackish way to use more powerful logic in your routes is http://www.ruby-forum.com/topic/42505.

Avatar

The one problem I keep having with routing is when you don't want the controller name in the route. For example, if you're doing a location based app, /texas/dallas/ is a lot more natural than /states/texas/cities/dallas. I do keep running in to a problem where two objects have the same scope, but you want to redirect to one if not found. i.e. /united-states/texas vs. /germany/munich. The way I've done this is ugly, but it works...kinda. Any suggestions would be helpful. I think there's a lot of voodoo with routing to most people.

Avatar

Finally getting to catch up on some of these... this is great Ryan!

Avatar

Charles, try:
http://railsontherun.com/2007/9/27/ajax-pagination-in-less-than-5-minutes

Avatar

@Marcello:

this would be really great. Thanks a lot for your efforts!!!

Avatar

While I generally do use simple methods like you defined above on map, I will sometimes take a different approach for those types of urls.

I generally start applications by removing the :c/:a/:id style routes and add a "site" controller for general site topics. The routes file might look like this at first:

map.site ':action', :controller => 'site'

This works well enough since it can be used pretty cleanly:

site_path('jobs') #=> /jobs

There are some pros and cons here. One is that the actions can be added easily, which is a good thing in initial development... but if you like to strictly protect interfaces exposed on the web, then you can add some constraints on action:

map.site ':action', :controller => 'site', :action => /(jobs|sitemap|about)/

That regular expression will ensure only certain actions can get called ( the ()'s are required to correctly match given the |'s -- in 1.2 at least).

Finally, I should note that it is rather easy to add a formatted route as well:

# here is where things like with_options help a little.
map.site ':action', :controller => 'site'
map.site ':action.:format', :controller => 'site'

site_path('jobs') #=> /jobs
site_path('sitemap', 'xml') #=> /sitemap.xml

This might come in handy if you have several types of clients connecting to your service.

Of course, there are probably places where the overhead of these slightly more dynamic routes might be harmful.

Avatar

I wonder if it would work advanced graphics. but let me try thanks anyway

Avatar

I will try and see how it works. The screencasts did work fine.Really Good Work!

Avatar

@rene and Ryan:

The translation is underway. At least the pdf manual shall be ready by the ende of the week. The code soon follows. =)

Avatar

Hi iceskysl, for charts I think you could use this:
http://elctech.com/2007/9/7/swfchart-generator

I didn't try it but like the results. It uses http://www.maani.us/xml_charts/index.php?menu=Gallery
which can be controlled also via PHP.

Nik

Avatar

Can you use the technique that you described for an arbitrarily nested creation? Assume that I want to have

Projects
Tasks
People

and I wanted to be able to add multiple tasks and multiple people on a single input form, can I still get away with that? It seems like the id substitution that Rails does may be a problem.

Thanks for the great work you do, I check in every week.

Avatar

你的英语讲的很好,内容也不错,我们很喜欢!
但是,有点小遗憾,就是有些东西讲的太少了.
我看过layout那部分,partial那部分没有涉及到!

Avatar

@jurglic,

FYI i just came across this... http://software.pmade.com/pdfreader

Looks like it was started in October but couldnt really find anything else on the net for reading PDFs.

Avatar

I tried out the PDF:Writer a while ago. One thing that bothered me is that it does not support Unicode. There is a hack to make it work with some European languages (documented in the rails wiki). However, Asian languages, Arabic, and so on are not supported. And since I read that Austin Ziegler isn't working on the PDF:Writer project any more there doesn't seem to be too much hope that this will change soon. Or does any one have new info on that?

Avatar

I've found a couple of issues here that maybe only affect me, but I'll post in case someone else experiences this.

First, the "should_destroy" attribute was showing up in the first item regardless of which item was removed. The issue was that the 'should_destroy' hidden fields had no value and so did not end up in the correct array. I switched to hidden_field_tag with a default 0 value and it's fixed.

Second, when passing strings with non-alpha chars the URL encoding for javascript was running once for each layer of the array. So '-n/a-' was becoming "-n%25252Fa-", I did a 3.times{ attr[:string] = URI.unescape(attr[:string])} within the task_attributes= method. Hackish, but it works.

Avatar

cool~thx.

and can anybody share somethings about “how to genarate reports chart in rails".

Avatar

Hi Ryan, just as a question is the code on new.rhtml valid html? I was just getting a little confused.

Avatar

Maybe you could do a future show about Mercurial on Rails?
http://www.selenic.com/mercurial/wiki/

Avatar

Ryan -- Thanks for the screencasts. They are extremely helpful.

@Paul, I made it work with checkboxes. I used check_box_tag. I use the checkbox value in the model (in def choice_attributes) to set the value of the field I want set, rather than setting it directly with the checkbox, like so:

attributes[:correct] = correct_choice_id.include?(attributes[:counter_id]) ? 1 : 0

It's a workaround but it works (and work s for radios, too). Then on the form end, I manually check the box like so:

<% is_checked = choice.correct == 1 ? true : false; %> and render the check box this way:
<%= check_box_tag('question[correct_choice_id][]',choice.id, is_checked,{}) %>

(that's on edit -- on new, when I don't have question.correct.choice I have named the checkbox with a counter from within the partial, and run essentially the same thing. I'm not sure if this will be clear or not but it does work for me so hopefully it helps.
 

Avatar

this videocast was extremely helpful to me, thank you for your hard work.

Avatar

@ryan, The following plugin makes :delete a :get action by default http://svn.soniciq.com/public/rails/plugins/iq_restful_monkey, then you just need something like:

# Controller
def delete
  @product = Product.find(params[:id])
end

# View (delete.html.erb)
<h2>Delete product </h2>
<% form_for @ product, :html => { :method => :delete } do |f| %>
  <p>Are you sure?</p>
  <p><%= f.submit 'Delete' %></p>
<% end %>

Avatar

@Marcello, I haven't tried RGhost yet. I'll have to look into it. Thanks for the suggestion!

@QuBit, a while ago I tried most of the options mentioned on this wiki page:

http://wiki.rubyonrails.org/rails/pages/HowtoGeneratePDFs

Out of those PDF::Writer was by far my favorite so I've stuck with it and haven't had any complaints. I should look into some more newer options though (RGhost).

@Paul, for simple PDFs I think a template view would work really well, but most of the PDFs I've done get fairly complex. In those cases it helps having an actual object with methods and variables.