开发者

Optional belongs_to relationship in Ruby

I'm migrating an application over to ROR from PHP that defines an object, let's call it a Document that can be created by a User who is either a registered user of the application, or an anonymous user who only gives their email address (in this case without an associated User account). There is no requirement for a visitor to create a User account, but they should still have the ability to create a Document.

In my model, I am first led to create the Document model that references the user with a belongs_to association. This however is not always the case. In pure SQL and PHP this is not hard, although it comes with it's own challenges, but I would like to model this in the "purest" Ruby/Rails way.

If a visitor d开发者_开发问答oes not have an associated User, their email address will be stored directly against the Document object.

To start the discussion, here are the snippets for each model.

# user.rb
class User < ActiveRecord::Base
  has_many :documents
end

# document.rb
class Document < ActiveRecord::Base
  attr_accessible :title, :description, :email_address

  belongs_to :user
end

My goal is to be able to retrieve all user documents using the standard dot notation:

user.documents

And to also check for the reverse relationship to see if the document belongs to a User or if it contains an email address.

if document.user.nil? ...

if document.email_address.nil? ...

I have read up on the has_one relationship but am not sure if this is the right path to go down.

Any help or suggestions would be appreciated, thanks!


You might want to consider making the User class more flexible so it supports anonymous users and only stores the email address.

It might make your code a bit cleaner.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜