RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

As a new person to tests and RSpec I have a problem getting my head around one thing:

How do the tests you write get integrated back into the code of the application? And how do methods like login_as_admin get used in the application?

Avatar

Asciicasts are great, but in this instance it is out of step. Quite different from the screencast.

Avatar

Webrat does not currently allow use of xpath, but there is a small patch to allow this at:

https://webrat.lighthouseapp.com/projects/10503-webrat/tickets/153-within-should-support-xpath

Avatar

Ignore my previous question. I was working on some code simultaneously and got confused... great cast Ryan.

Avatar

Ryan, as always, an extremely helpful railscast. A couple of small points.

The paypal public key is different for the sandbox than it is for the production site. So you need to download them separately and name them differently (if you are going to store both in the same folder). I then needed to add another entry to the app_config.yml file called paypal_cert_name and use it when loading the pem files.

Speaking of app_config. I found it helpful to add an "all" section at the top of the file, and modify the load_app_config.rb file to merge the "all" with the environment specific settings. (i.e APP_CONFIG = YAML.load(raw_config)["all"].symbolize_keys.merge(YAML.load(raw_config)[RAILS_ENV].symbolize_keys))
This allows me to have some settings which span all environments, and can be overwritten in any of them if needed.

Once again, thank you for your great contribution to improving life for rails developers.

Avatar

For me, the current_user and current_user_session controller methods work only in the development environment. When controllers are kept in memory across requests (as in production or test environment) the @current_user_session variable gets assigned once and is never updated, making it impossible to log out or switch to a different user. Is anyone else having this problem? Am I missing something?

Thanks, Ryan, for another fantastic episode. Authlogic has really cleaned up my apps.

Avatar

Hello, I love your screencasts and you have a unique gift of breaking down potentially complicated concepts into very easy to understand chunks.

A REQUEST

Can you at some point address how to build more complicated layouts restfully. For example a products page in which a news feed is also fed in as the sub menu (which also appears on other pages) where would the view be fed with this data in a pure REST environment.

Many thanks

Avatar

How do you resolve circular associations in factories? I have an account that contains a collection of users one of which is the account owner:

Factory.define :account do |f|
  f.state "pending"
  f.association :owner, :factory => :user
end

Factory.define :user do |f|
  f.sequence(:first_name) { |n| "factory_user#{n}" }
  f.last_name "Smith"
  f.password "test"
  f.password_confirmation { |u| u.password }
  f.email { |a| "#{a.first_name}@example.com".downcase }
  f.eula "1"
  f.association :account
end

It loops in to infinity and crashes the tests... Is there an obvious way around this? Thanks for your help and thanks for a great set of casts.

Avatar

I have posted a version for people with Ubuntu 9.04 to give this a shot. I hope you guys dont mind. I did give credit at the top of the post.

http://aslambilal.blogspot.com/2009/06/beginning-with-cucumber-for-ubuntu-904.html

Avatar

What about:

svn propset svn:ignore "*.sqlite3" db/

?

Avatar

Hi,
First of all thanks for making this tutorial, someone told me it was a good one to learn from.

Here's my current problem

~/www/blog$ cucumber features -n
bash: cucumber: command not found

Any idea what i can do ? i haven't been able to find a fix on Google ( perhaps i was searching improperly )

Avatar

Hey everyone, I'm a complete beginner at ruby and rails and was wondering how you can access the username or email address of an existing user object without using the a form construction.

I attempted something along the lines of:

<% for user in @users %>
<tr>
<td><%=h user.name %></td>
<td><%=h user.email %></td>
</tr>
<% end %>

but clearly the user object doesn't have methods like name or email. Are there methods for getting these, or does this require a completely different strategy. Sorry if this question is too basic.

I'm getting errors like the following:
undefined method `name' for #<User:0x722b080>

Avatar

Are you using :value for your textfields? :value=>@course.duration/3600

Avatar

Hey Guys,
Don't panic if you are getting below error when you tried to run "cucumber features -n":

missing argument: -n (OptionParser::MissingArgument)

You are getting this error because cucumber version is now updated.

Try to run "cucumber features" and it will work fine!!!

Avatar

Hey Guys,
Don't panic if you are getting below error when you tried to run "cucumber features -n":

missing argument: -n (OptionParser::MissingArgument)

You are getting this error because cucumber version is now updated.

Try to run "cucumber features" and it will work fine!!!

Avatar

Hello All,
I wanted to implement sphinx search.
I have following models.

Blog
# post model has column "channel_feature_id"
has_many :posts, :foreign_key => "channel_feature_id"

------
Post
# Indexes for thinking
sphinx define_index do
indexes title
indexes abstract
indexes body
#indexes comments.body, :as => :comment_content
# OPTIONAL: keeps search index update
# First, add a boolean column to your model,
# named 'delta', and have it default to true.
# Then uncomment following line.
#set_property :delta => true
end

belongs_to :blog
has_many :comments
# GET published posts
named_scope :published, :conditions => [ 'published = ?', true ]
------
Comment
belongs_to :post
------

In my search action i have
blog.posts.published.search ( params[:search] )
i am unable to figure out error.

Missing Attribute for Foreign
Key channel_feature_id

here is full trace.......
vendor/plugins/thinking-sphinx/lib/thinking_sphinx/active_record/has_many_a ssociation.rb:18:in
`search'
/home/sandip/.gem/ruby/1.8/gems/activerecord-2.1.2/lib/active_record/named_ scope.rb:158:in
`send'
/home/sandip/.gem/ruby/1.8/gems/activerecord-2.1.2/lib/active_record/named_ scope.rb:158:in
`method_missing'
/home/sandip/.gem/ruby/1.8/gems/activerecord-2.1.2/lib/active_record/base.r b:1857:in
`with_scope'
/home/sandip/.gem/ruby/1.8/gems/activerecord-2.1.2/lib/active_record/associ ations/association_proxy.rb:164:in
`send'
/home/sandip/.gem/ruby/1.8/gems/activerecord-2.1.2/lib/active_record/associ ations/association_proxy.rb:164:in
`with_scope'
(__DELEGATION__):2:in `__send__'
(__DELEGATION__):2:in `with_scope'
app/controllers/blogs_controller.rb:36:in `search'

Thanks,
Sandip

Avatar

<script src='http://pastie.org/524112.js'></script>

Avatar

Thanks for this Ryan!

I'm trying to use virtual attributes on a model that maintains a 'duration' field, which is an integer of seconds. In my model I'd like to be able to represent this duration value as 'hours' & 'minutes'. The model saves correctly, however I can't seem to find a way to initialise hours & minutes from the database. Could you help?

http://pastie.org/524093

Avatar

to Zasheir

with machinist you need to change your step definitions as following
Given /^(.+) records$/ do |model, table|
  model = model.gsub(/\s/,'_').singularize
  klass = eval(model.camelize)
  klass.transaction do
    klass.destroy_all
    table.hashes.each { |hash| klass.make(hash) }
  end
end

Avatar

I'm a little confused. I get the 'why' and the 'how'. But not quite the 'what'. Anything in attr_accessible is hackable so why would you want anything in it?

Avatar

hi, thank you for examples, my question is that if i want to show the search results how can i show that in the same view , thank u very much:)

Avatar

Anyone have any links to using stubs from Factory_Girl, I can't seem to get it to work. I have inherited code where the models have a dependency of A belongs to B which belongs to A prime (polymorphic).

Think sales person belongs to a region which has a manager (which is just a polymorphic version of the [sales]Person table). With fixtures it "auto" built the tables so I didn't need to worry about initial validations, I can't figure out how to do that with Factories.

Avatar

some newbies problems and solutions:
1) impossible to download prawn or prawnto: try again ! I need to do this 5 times
2) Error with Memoizable: Comment the 3 related lines in compile_support.rb
3) Blank page => be sure to have this line in respond_to format in your controller: format.pdf { render :layout => false }

Avatar

As usual, gr8 work!!
Is it possible for you to do an episode on in_place_editor? It looks like they have a plugin for it, but none of them have a good documentation.

Thanks and keep up the good work.

Muntasir

Avatar

This railscast was still useful to me today, over 2 years later. Thanks :)

Avatar

code for my last post seperately -

for view -
<script src='http://pastie.org/521362.js'></script>

for controller -
<script src='http://pastie.org/521366.js'></script>

Avatar

Thanks a lot Ryan for the highlighting the hidden secrets of Rails ActiveRecord and all others. Mass assignment made easy via params[:project][existing_task_attributes][]...

A tip for someone who might be hunting for Mass assignment in a belongs to many through a third connecting table Scenario -

Proposal can have many Sections via Proposalsections.

Decided by a checkbox to create/delete a new/existing Proposalsection record for a Proposal.
----
code for view - with checkboxes
for openingsection in @sections
<li class="topItem clear">
<%@pso=Proposalsection.find_by_proposal_id_and_section_id(@proposal.id, openingsection.id)%>
<% if @pso.nil? %>
<%= check_box_tag "proposal[proposalsection_attributes][][section_id]", openingsection.id %>
<% else %>
<%= check_box_tag "proposal[existing_proposalsection_attributes][#{@pso.id}][section_id]", openingsection.id, :checked=>true %>
<% end %>
<%= openingsection.name %></li>
end
-----
code for controller - saving Proposalsections with Proposal fields

params[:proposal][:existing_proposalsection_attributes] ||= {}
@proposal=Proposal.find(params[:id])
@proposal.update_attributes(params[:proposal])
  end

It worked for me after wasting full day tweaking over it.

Avatar

Ryan i had
You have a nil object error

is this parameter right?
category_attributes"=>[{"id"=>"83"}]}

i want to bind category or categories to a product.

Avatar

@J, good question. Here Tag doesn't have any validations (it is too simple), but if there are validations on the model you'll definitely need to take that into consideration.

One solution is to do "create!" (with a bang) to ensure an exception is raised if the validation fails. However this is not pretty to the end user. Unfortunately I don't know of an easy way to handle validations in a pretty way here.

@Vincent, f.error_messages has been around for quite some time, I think since Rails 2.0 but I'm not positive.

@Robin, It should not orphan any Tagging records (the tags= method takes care of this), but Tag models will continue to exist even if they do not have articles assigned to them.

I don't think that is much of an issue here, but there are a couple ways around this. One is to add an after_destroy hook on tagging to check if it is the last one and remove the tag as well. Alternatively you could set up an external recurring task to loop through all tags and remove empty ones.

Avatar

Two years ago this stuff could be called complex, but Ryan, as you just say, today we are using it in all our everyday projects.

These days it really shouldn't be called hard or complex, we probably need a different approach to the problem.

Avatar

The option to set the width of cells in a table has been changed from :widths to :column_widths in Prawn 0.4

I haven't seen this documented in the examples at http://www.cracklabs.com/prawnto , hope this helps!

Deb

Avatar

I'm using Rails 2.3.2 - and doing content_for in the layout itself will NOT make that content visible if you yield in the layout as well.

i.e. if in application.html.erb, you do 'content_for :javascript', etc... and do a 'yield :javascript' in the same layout, it will not work. I'm not sure how to get the required behaviour since I was depending on this...

Annoying.....

Avatar

This code could potentially lead to orphaned tags and taggings, couldn't it? I don't know what meta-magic goes on behind the stage, but the code for cleaning up after yourself does seem to be missing?

Otherwise, great job :)

Avatar

Madan Kumar Rajan,

attr_writer creates that code automatically. Search about meta-programming :)

Avatar

great cast and really useful plugin.

however I wonder if you checked the single_access_token feature.. i am trying to work with it but it seems that i have something wrong in configuring it to work with all requests.

many thanks

Avatar

Boo to sniffles, get well soon.

That's the first time I've ever seen f.error_messages.. How long has that been available?

Avatar

and don't forget that this code also allows you to remove tags from an article.

and be aware of unused tags if you heavily add and remove tags, since only taggings are destroyed.

Avatar

Dear Ryan,

This episode is as great as it always use to be. I have one doubt though...
You have defined task_names as writer. It means it wont be defining

def task_names=(name)
  @task_names = name
end

Then how does its value get assigned?

Thanks,
Madan Kumar Rajan

Avatar

Thanks for this great episode :) However, I did have one question. What happens if the virtual attribute model fails validation?

Avatar

how can we handle adding new product(and its category)procedure using categorization model?
before that , i've been using category_id column in products table and i can add using form_for(@product).
Now how can i relate product and its category in the same form page?

Avatar

if it weren't for these, my RoR understanding wouldn't be what it is.

Good..

Avatar

I'm using rails 2.3.2 and I tried using

xml.link articles_url(:format=>:rss)

as shown in comment 50 but I get a blank page when I go to articles.rss

Any help?

Avatar

Ryan,

Nice post, I have an issue here.
The caching does not seem to work for the @user_session in the ApplicationController
Each time I reload the page it is re-initialized (the __new__ method is executed) and I cannot figure out why. Is it because I'm working on the development environment ?

Thanks for your help.

Avatar

Awesome railcast Ryan.

I too am eager to learn an authorization overlay on authlogic - at the minimal I would like to add admin status to some of the users.

Avatar

Since this was not clearly stated in text form I thought I would include this little snippet from the documentation on named_scope:

-----------------------
Unlike Shirt.find(...), however, the object returned by Shirt.red is not an Array; it resembles the association object constructed by a has_many declaration. For instance, you can invoke Shirt.red.find(:first), Shirt.red.count, Shirt.red.find(:all, :conditions => {:size => ‘small’}). Also, just as with the association objects, named \scopes act like an Array, implementing Enumerable; Shirt.red.each(&block), Shirt.red.first, and Shirt.red.inject(memo, &block) all behave as if Shirt.red really was an Array.

Avatar

Hey Ryan,

Thanks for another great podcast. I was successful setting up a mailer on my user model, but when I tried to apply my learning to set up a mailer on another model I got stuck.

My problem: the Feedback model data isn't getting passed to the view, resulting in a nil error.

Would you have a look at my code and tell me if you see anything I'm missing?"

http://pastie.org/517714

Avatar

The pref pane download link from the link in the show notes doesn't work anymore. Instead I went here http://www.fngtps.com/2008/12/passenger-preference-pane-v1-2

Avatar

@Yuri

I'm having the same problem. Were you able to work it out?

thanks

Deb

Avatar

The link to http://railsmanual.org/ no longer takes you to the an API. It redirects to a site that may not be safe for work.

Avatar

Could this work with has_and_belongs_to_many? I have a multi-site CMS where each page can belong to multiple sites. The nesting would need to happen in pages_sites.