开发者

Do you need new and create methods for profiles?

开发者 https://www.devze.com 2023-02-20 13:35 出处:网络
Let\'s say Profile is it\'s own model, and a User has_one Profile. When a user is created s/he should automatically be given a default empty profile. So I\'m assuming I don\'t need a new开发者_如何转开

Let's say Profile is it's own model, and a User has_one Profile. When a user is created s/he should automatically be given a default empty profile. So I'm assuming I don't need a new开发者_如何转开发 or create action for the profiles controller, and only update, edit, and show. Is this assumption correct? If so, how do I automatically generate an empty profile? In my user create method?


Yeah, you can deal with creation in the user model. Defining a has_one association automatically includes methods for building and creation (in this case it would be User#create_profile and User#build_profile). A good practice is to set up a before_create callback that calls build_profile, so that you won't get an orphaned User record if the profile doesn't save.

As far as controllers are concerned, I usually don't even like to make separate controllers for user profiles. Since there will always be one Profile record for every User record you can think of profile attributes as being logically equivalent to User attributes (they are put in their own table mainly organization's sake). That way you can just tack on profile stuff to the usual User CRUD operations. If you really like the idea of a separate profiles_controller, consider setting it up as a nested resource, since you will always have a user_id whenever you are dealing with a profile.

0

精彩评论

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

关注公众号