2

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

  • How do I reference it with has_many? Should I use has_many :user_has_messageses?

  • How do I do joins? I have tried User.joins(:user_has_messages) and it is sad :(

Question:

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

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

Satchel
  • 16,414
  • 23
  • 106
  • 192

3 Answers3

4

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

class OtherClass < ActiveRecord::Base
  has_many :user_has_messages, :class_name => 'UserHasMessages'
end
tommasop
  • 18,495
  • 2
  • 40
  • 51
3

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 :)

nathanvda
  • 49,707
  • 13
  • 117
  • 139
2

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 :)

Spyros
  • 46,820
  • 25
  • 86
  • 129