开发者

belongs_to with default fallback

开发者 https://www.devze.com 2023-02-15 19:34 出处:网络
Currently, My Rails (3) app creates objects before their relation is known (I store the Comment, then ask the user to log-in/sign-in to validate that comment, after which the Comment gets a User assig

Currently, My Rails (3) app creates objects before their relation is known (I store the Comment, then ask the user to log-in/sign-in to validate that comment, after which the Comment gets a User assigned).

I'd like to make sure each Comment falls back to a user at all times. To avoid having to test everywhere for @comment.user. Ensuring a user also allows me to validate_presence.

I can see two ways, both seem quite ugly. Maybe I am missing some feature of Rails or ActiveRecord.

  1. In the seed or migration, create a user with ID 1, call that anonymous and assign that as fallback.
  2. in comment.rb check for user_id on load, if null, assign a User.new to it.

How is this usually 开发者_StackOverflow中文版done?


How about adding user records for all comments. Even for not signed-in users. This is just one more record per anonymous comment. And in user records you can keep last IP address and other stuff like max anonymous comments per day.

After user sign-in, reassign comments to the right user and delete temporary user. For new user sign-ups update temporary user records to verified state.

Notice that each anonymous comment has owner, but the user isn't verified. And verification state can be treated as user attribute.

Yes, it is possible to keep unverified users data in session. However sessions sometimes are configured to be stored in a database. So result is the same as storing temporary users in main users table in terms of disk usage, but the data is more fragmented.


Maybe temporarily store necessary stuff in session, not in database? I don't like the idea of storing partially complete records in database. It is a risky play with database integrity. Alternatively, you could create a table with text column which would contain those incomplete objects serialized.

0

精彩评论

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