oobie11
oobie11

Reputation: 925

How do I build a form for creating a post that belongs to a user?

Im a rails beginner on rails 4 and I'm learning by doing. I have users and posts on my simple test app. My user model

has_many :posts

My post model

belongs_to :user

I have a form partial for creating a new post like this

<%= form_for @post do |f| %>
<% if @post.errors.any? %>
    <ul>
        <% @post.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
        <% end %>
    </ul>
<% end %>
<%= f.label :title %>
<%= f.text_field :title %>
<br/>
<%= f.label :body %>
<%= f.text_area :body %>
<br/>
<%= f.submit %>

My routes file

resources :users do
  resources :posts, except: [:index]
end

When i try to create a new post, I get a

No route matches [POST] "/posts"

Im assuming that its not working because of how my form partial is set up. I think that the

form_for @post do |f|

needs to be different, but I'm not sure what to change it to. Any suggestions? Thanks.

Upvotes: 0

Views: 60

Answers (2)

mike
mike

Reputation: 859

for this route

resources :users do
  resources :posts, except: [:index]
end

You must create form with

form_for [@user, @post] do |f|

or

form_for [current_user, @post] do |f|

Upvotes: 2

Yoann Augen
Yoann Augen

Reputation: 2036

You should remove the except: [:index] from the route. That must block /posts access.

Upvotes: 0

Related Questions