Not signed in (Sign In)

SkillShare - A place to discuss Web Standards and Web Design topics

Categories

Vanilla 1.1.5a is a product of Lussumo. More Information: Documentation, Community Support.

    •  
      CommentAuthorjskopek
    • CommentTimeJul 18th 2006 edited
     permalink
    I'm having a bit of a problem with custom associations. Say I have a custom has_one association :latest_comment in model Post

    class Post < ActiveRecord::Base
    has_many :comments
    has_one :latest_comment,
    :class_name => "Comment",
    :order => "created_at DESC"
    end

    This code does not seem to create any exceptions, yet when I reference the association :latest_comment from another Controller - like so:

    test_comment = Post.latest_comment
    (OR)
    test_comment_body = Post.latest_comment.body

    It gives me the following error:
    "undefined method 'latest_comment' for Post:Class"

    Shouldn't the association create these methods automatically? What am I doing wrong? Should I specify attr_accessor :latest_comment?
    I can't seem to find anything on the internet that refernces this problem. Any of you have any ideas?
    Thanks in advance!
    •  
      CommentAuthorjskopek
    • CommentTimeJul 18th 2006
     permalink
    I've figured out the problem. I was trying to reference the method directly from Post, when I should have created an instance of it. This code will work:

    test_comment_body = Post.new.latest_comment.body

    If anyone knows a way to reference methods without having to create a new instance (is this even possble?), can you let me know?
    Thanks
Add your comments
    Username Password
  • Format comments as (Help)