Model Relations

Hi,

I am creating my databases and models and I need to use some
relationships. I am very new at this so any help or info at all would be
great. :slight_smile:

The concept is:
There are three resources: people, items and tags.

* An item belongs to one person, the creator.
* A person can create many items.
* An item can have many tags.
* A tag can be used on many items.

Here my models:

You could use has and belongs to many or has many through. Either way
you will need another table (the join table for the relationship
between tags and items), the existing tables are fine as is.
You might find http://guides.rubyonrails.org/association_basics.html
helpful.

Fred

You can shorten this part up by using Tag.find_or_create_by_name, one
of the dynamic finder methods.
And I'd add a generic warning to NEVER use #{} interpolation directly
in anything you're feeding to an AR conditions parameter, unless you
want to relearn the lesson of little Bobby Tables...

The final code will look something like:

  def create
    # find item, put in @item
    @item.tags = params[:tags].split(' ').map do |tag|
      Tag.find_or_create_by_name(tag)
    end
    # do whatever else
  end

Alternatively, you could encapsulate this behavior in the Item model,
using a virtual tags_attr or the like to do the parsing. I'd recommend
that you take a look at some of the approaches taken by
acts_as_taggable and it's descendants.

--Matt Jones