Having trouble setting up model relationships

I’m working on a new project, and I’m stuck on making some seemingly
simple model associations work. I have the following models which I’m
trying to get to play nice:

  • entry
    belongs_to :users
    has_and_belongs_to_many :categories
  • category
    has_and_belongs_to_many :entries
  • categories_entries (the join model)

As I loop through entries in the view, i want to be able to be able to
list any associated category name next to the entry name. So in the
view I’d like to write, entry.category.name to access the category
name, though when i try that, I get “undefined method `category’ for
#Entry:0x256c0dc.”

How would I set this up correctly? I’ve blown apart the associations
many times at this point and I haven’t stumbled upon the correct way
to do this. Any help would be greatly appreciated.

Thanks,
-A

ressister wrote:

I’m working on a new project, and I’m stuck on making some seemingly
simple model associations work. I have the following models which I’m
trying to get to play nice:

  • entry
    belongs_to :users
    has_and_belongs_to_many :categories
  • category
    has_and_belongs_to_many :entries
  • categories_entries (the join model)

Firstly, if you write unit tests for this, and if you fill your
entries.yml and
categories.yml files with sample fixtures that illustrate your project,
you can
start with simple test cases that explore how the relations work.

As I loop through entries in the view, i want to be able to be able to
list any associated category name next to the entry name. So in the
view I’d like to write, entry.category.name to access the category
name, though when i try that, I get “undefined method `category’ for
#Entry:0x256c0dc.”

That is exactly because an entry has many categories. So name them
all:

entry.categories.map(&:name).join(’, ')

Write that into a unit test, and then into your view. If you go with it,
refactor it into a reusable method: entry.category_names.

However, if your users don’t want to see extra category names, you must
find
some way to distinguish them:

entry.categories.find_by_distinguishing_field(foo).name


Phlip

Hi Philip, thanks for the reply. I’m just trying to get the
association working - to be able to link through the join table so I
can access the category for an entry. I’ve decided that I only want
an entry to belong to one category. Still, I’m having trouble.
Here’s where I am right now:

  • entry

    • has_one :category
  • category

    • has_many :entries
  • entry_category (I renamed this join table)

    • belongs_to :entry
    • belongs_to :category

What’s missing? I’ve tried in the entry model to use
has_one :category, :through => :entry_category but i got an error
about not being able to find the key(s). Let me know if you have any
additional thoughts.

Thanks again for your help.

-A