Satchel
Satchel

Reputation: 16734

What should I do if I named a Model in Rails 3 plural?

I created a model called UserHasMessages based on some SO postings. I think this seems to be creating some challenges for me:

Question:

Should I somehow change the name to UserHasMessage, and if so, how?

If I keep as plural, how do I handle these cases?

Upvotes: 2

Views: 1652

Answers (3)

nathanvda
nathanvda

Reputation: 50057

You could add a new migration

rails g migration rename_user_has_messages

inside it you write:

class RenameUserHasMessages < ActiveRecord::Migration
  def self.up
    rename_table :user_has_messages, :user_messages
  end

  def self.down
    rename_table :user_messages, :user_has_messages
  end
end

(the table is always plural)

Run the migration.

Rename your file from user_has_messages.rb to user_message.rb, and rename your class from UserHasMessages to UserMessage.

Done :)

Upvotes: 3

Spyros
Spyros

Reputation: 48636

Avoid class names that end with an S, like the devil avoids holy water. The name UserHasMessages is a very poor choice. You do not create a db table to check for something. Instead, you have a User model, a Message model and a UserMessage model. Then, if you want to check user messages, you just create a method that does that. The association should be :

User has many messages through user_messages

and you would get user messages like current_user.messages .

I highly advise you to change your design to the one i described :)

Upvotes: 2

tommasop
tommasop

Reputation: 18765

You can use the same syntax you use with legacy tables:

class OtherClass < ActiveRecord::Base
  has_many :user_has_messages, :class_name => 'UserHasMessages'
end

Upvotes: 4

Related Questions