开发者

Multi Model Form in Rails 3

开发者 https://www.devze.com 2023-03-04 07:27 出处:网络
I\'m still a bit of a n00b when it comes to rails, however, I do have a question a开发者_如何学Cs to how to go about a multi-model form.

I'm still a bit of a n00b when it comes to rails, however, I do have a question a开发者_如何学Cs to how to go about a multi-model form.

Basically, I have an event, and the user needs to be able to register for the event and provide a credit card for charging the event to. The credit card (I won't be holding the actual data for the CC, authorize.net will, but I need to keep a token representing the card) will live with the user so they can sign up for other events in the future. So, I want the user to be able to edit this in the future, and the card isn't specific to a single event. This doesn't seem like something I'd use nested routes with, does it?

I have a feeling this is fairly simple, but I guess I'm just not entirely sure how to do it. Can I used nested models (not routes) and still update each portion independently?


If I understand your question, then yes you can. I think you mean something like this:

class User < ActiveRecord::Base
  has_one :credit_card
end

If that's correct, then the first step is to add this to the User class:

class User < ActiveRecord::Base
  has_one :credit_card
  accepts_nested_attributes_for :credit_card
end

At this point you could just set up a "users" resource in the routes file and you could edit the credit card through a fields_for method in your edit view:

form_for @user do |f|
  f.fields_for :credit_card do |ff|
    ff.label :number
    ff.text_field :number
  end
  f.submit
end

Does that help?


Since Formatting is not allowed in comments, I am making a answer for it.

Thanks @twmills for your answer,

I am also new to rails. I have a question, will it work in case where I have following relationship:

class User < ActiveRecord::Base
  has_many :credit_cards, :dependent => :destroy
  accepts_nested_attributes_for :credit_card
end

class CreditCards < ActiveRecord::Base
  belongs_to :user
end

In above case, you can't create a CreditCard object unless you have parent user. Will f.fields_for :credit_card do |ff| also create an object of CraeditCard @user to f?

As per my understanding, this is not possible as how will be tell the view, which credit card to edit.

Secondly, On edit, this is fine but can I do something similar at the time of user creation. i.e. getting his credit card information at the time of user creation.

0

精彩评论

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

关注公众号