سؤال

I have a single form.

That form is currently in the View for the model Message.

Sometimes, I want to be able to associate a Contact (first name, last name) with that particular Message. Contact is its own Model.

When the form is submitted, Message has a contact_id attribute. I would want that contact_id to be associated, but also to create a new Contact.

How do I do that in Rails 3?

هل كانت مفيدة؟

المحلول

It seems that you want both Contact and Message objects created from the same form and make them associated. As I told you in a previous question. form_for can take both stand alone values and even other objects values.

_form.html.erb

<% form_for :message do |f| %>
  <%= f.test_field :some_field %>
  ..
  ..
  <%= text_field :contact, :first_name %>
  <%= text_field :contact, :last_name %>
  <%= f.submit %>
<% end %>

messages_controller.rb

def new
  @message = Message.new
  @contact = Contact.new
end

def create
  @message = Message.new(params[:message])
  @contact = Contact.new(params[:contact])
  @contact.message = @message
  if @contact.save # saves both contact and message if has_one relation is given in models
    ..
  else
    ...
  end
end

But this being said, it is better to use Nested form model. For that, you will have to write code centered on contact.

contacts_controller.rb

def new
  @contact = Contact.new
  @contact.message.build
end

def create
  @contact = Contact.new(params[:contact])
  if @contact.save
    ..
  else
    ..
  end
end

_form.html

<% form_for :contact do |f| %>
  <% f.fields_for :message do |p| %>
    <%= p.text_field :some_field %>
    ...
  <% end %>
  <%= f.text_field :first_name %>
  <%= f.text_field :second_name %>
  <%= f.submit %>
<% end %>

For this, you will have to specify accepts_nested_attributes_for :message in Contact.rb

نصائح أخرى

With a Nested Model Form.

Give a look at: http://asciicasts.com/episodes/196-nested-model-form-part-1

It's based on Rails 2, but there isn't much to be done in order to make the code compatible with Rails 3.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top