Associating Two Models in Rails (user and profile)

后端 未结 3 852
無奈伤痛
無奈伤痛 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条回答
  •  梦毁少年i
    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.

提交回复
热议问题