简体   繁体   中英

How to use an create two instance in just one for, using two controllers

I am new to Rails, and has been following several tutorials that lack the completeness of a real-time web-app. They show how to use a model-view-controller in each file, but I haven't found one that show how to create various models with just one form, using the methods of several controllers using association between them.

Use case:

I have a User model, an Account model that are associated. I tested it in irb, but in the controller, I need to have a User object to associate the user with the account, but when creating the user, it's just the form data for the user, managed by the user controller, as shown in the tutorials, and the accounts, separated in it's own view, managed by it's own controller.

how can I use the User created in the user controller, when creating an account. What I would like to do the most, it's create account when creating the user, in the same view. But what i really like it, it a tutorial that shows how to have Total Control over the views and controller, and how to accomodate those elements to your design. Thanks

What you're looking for could be "nested attributes".

Here's the detailed documentation: http://apidock.com/rails/ActiveRecord/NestedAttributes/ClassMethods/accepts_nested_attributes_for

Otherwise, you may be running into Rails being it's own special variant of MVC. You don't call controller actions from other controllers - controllers handle the response to a web request, not interaction with the data. That's for models.

It's a little hard to tell what you're asking for, but I think you're actually just getting tripped up on unexpected simplicity. Everything in your user-model0 is accessible through the User object / singleton / class thing. For example, User.find(1) . User is accessible in all controllers and all views (as is Account ). Just use them when you need to!

Edits from comments:

def action
  user = User.new(params[:user])
  user.save

  account = Account.new(params[:account])
  account.user = user
  account.save
end

However! This way of doing things pretty much can't nicely handle errors. What you really want is to use nested attributes, which lets you create the account as part of the user, or vice versa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM