Ignacio Palma Balboa Ignacio Palma Balboa - 1 year ago 72
Ruby Question

How do i make one form for two related models?

I want to write data for 2 different models that are related to each other like this:

class Post < ActiveRecord::Base
has_many :roads
accepts_nested_attributes_for :roads, :allow_destroy => true

class Road < ActiveRecord::Base
belongs_to :post

Of course de roads table has a "post_id column". My form_for in the post view looks like this

<%= form_for @post do |f| %>

<div class="form-group">
<%= f.label :Tu_Nombre %>
<%= f.text_field :creador, class: "form-control" %>

<div class="form-group">
<%= f.label :año %> (Cuando fue tu experiencia?)
<%= f.text_field :año, class: "form-control" %>

<div class="form-group">
<%= fields_for :roads do |r| %>
<%= r.label :principio %> (desde?)
<%= r.text_field :principio, class: "form-control" %>

<%= r.label :final %> (hasta?)
<%= r.text_field :final, class: "form-control" %>
<% end %>

<div class="form-group">
<%= f.label :historia %> (Cuentanos la historia de tu viaje!)
<%= f.text_area :historia, class: "form-control", size: "50x15" %>

<%= f.submit class: "btn btn-success" %>

<% end %>

Finally my posts_controller create method

def create
@post = Post.new(post_params)

if @post.save
redirect_to @post, notice: 'Post was successfully created.'
render :new

with the private

def post_params
params.require(:post).permit(:historia, roads_attributes: [:pricipio, :final, :post_id])

The post is submitted and if i check the console all the atributes for post has been saved but the ones for road, has not. How can i use just one form two make records for these two models and that the post_id gets registered so i can relate the tables?

Thanks a lot!!

Answer Source

Update your posts_controller new method to include .build

def new
  @post = Post.new
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download