开发者

Why does this user not have an invitation?

I have a form that creates a signed_user. This is the first line of the form:

<%= form_for(setup_user(@signed_user)) do |f| %>

The setup_user is in my application helper:

def setup_user(user)
  user.tap do |u|
    u.build_invitation
  end
end

These are the model associations:

signed_user model:

has_one :invitation, :foreign_key => "sender_id"

invitation model:

belongs_to :sender, :class_name开发者_如何学运维 => 'SignedUser'

So why is a user being created without an invitation? I checked my console and the user's invitation is nil...


What you want is a nested form. All the details are available in the article but basically make sure you use accepts_nested_attributes_for in your SignedUser model.

class SignedUser < ActiveRecord::Base

  ...

  has_one :invitation, :foreign_key => "sender_id"
  accepts_nested_attributes_for :invitation, :allow_destroy => true
  ...

end

If you want your form to modify attributes from the Invitation model (in addition to attributes from the SignedUser), you'll also need to use fields_for in your form. For example:

    <%= form_for setup_user(@signed_user) do |f| %>

      <%= f.label :name %>
      <%= f.text_field :name %>

      // More user form fields

      <%= f.fields_for :invitation do |cf| %>

        <%= cf.label :event_name %>
        <%= cf.text_field :event_name %>

        // More invitation form fields

      <% end %>

      <%= submit_tag %>
    <% end %>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜