Associating Two Models in Rails (user and profile)

后端 未结 3 832
無奈伤痛
無奈伤痛 2020-12-29 16:42

I\'m new to Rails. I\'m building an app that has a user model and a profile model.

I want to associate these models such that:
- After the user creates an

相关标签:
3条回答
  • 2020-12-29 17:26

    For usability sake the profile should be part of the user model, or you should create your account and at least the base of your profile all in one go, as a user I i registered and then had to fill in another form I think I would be pretty annoyed.

    The upside of this is that either way you can do this with one form. I'd look at the railscasts on complex forms and if you can handle a very modest financial outlay then the pragmatic programmers series on Mastering Rails Forms is a total winner.

    0 讨论(0)
  • 2020-12-29 17:48

    When a user is created, the client is redirected to the new action in the ProfileController without an id. You need to explictly pass the user's id in the parameters. It's an idiom to pass the reference to the entire object, not just the id.

    # app/controllers/users_controller.rb
    
    def create
      # ...
      redirect_to new_user_profile_path(:user_id => @user)
      # ...
    end
    

    Notice that I'm using new_user_profile_path and not new_profile_path. The former is the nested resource that you defined in routes.rb. You should delete map.resources :profiles because a profile cannot exist without a user.

    0 讨论(0)
  • 2020-12-29 17:48

    Because user_id doesn't exist or is not created in the profile database. When creating user

    0 讨论(0)
提交回复
热议问题