I have two models,
class User < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to: user
end
I'm using formtastic gem
, consider in edit
action of users_controller
. All required user
and associated posts
attributes of the form will be prefilled by formtastic form
code:
<%= semantic_form_for @user do |f| %>
<%= f.input :name %>
<%= f.inputs :posts do |p| %>
<%= p.input :title %>
<%= p.input :comment %>
<% end %>
<% end %>
For instance i'm having a @user
and two posts
associated.
while doing @user.posts
, the result be like.
[
[0] #<Post:0x0000000aa53a20> {
:id => 3,
:title => 'Hello World',
:comment => 'Long text comes here'
},
[1] #<Post:0x0000000aa53a41> {
:id => 5,
:title => 'Hello World 2',
:comment => 'Long text comes here too'
}
]
So the form will contain two posts field to edit.
Actually, I want another blank post form before those two posts.
This can be easy achieved by inserting a new empty post
object to @object.posts
result at 0th position.
So, the @object.posts
result i want should exactly look like,
[
[0] #<Post:0x0000000aa53a50> {
:id => nil,
:title => nil,
:comment => nil
},
[1] #<Post:0x0000000aa53a20> {
:id => 3,
:title => 'Hello World',
:comment => 'Long text comes here'
},
[2] #<Post:0x0000000aa53a41> {
:id => 5,
:title => 'Hello World 2',
:comment => 'Long text comes here too'
}
]
Any solutions to get this structure from @user.posts
?
Inside the #edit
action do something like :
def edit
#... your code
@user.posts << Post.new
end