Reputation: 151
Thanks guys. I've solved the problem. It's because when I enter the posts/new
page. The new action creates a dummy @post
with nil attributes. Since the @post
exists, the edit & delete link in the sidebar appears. However, the edit_post_path
doesn't work because the @post.id
is nil
. Then the error occurs. So I just changed <% if @post %>
to <% if @post && [email protected]? %>
and it works. -- p.s. The rails error message is quite confusing.
I'm new to rails and just built a simple app and saw the error when I click a link to create a new post:
No route matches {:action=>"edit", :controller=>"posts"}
The rake routes
result:
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
The routes.rb file has resources :posts
in it.
The link is : <li><%= link_to "New Post", new_post_path %></li>
The new & edit method in PostsController
:
def new
@post = Post.new
end
def edit
@post = Post.find(params[:id])
end
I can show the post, edit the post and delete the post. But whenever I want to click the link to create a new post, the error occurs. I can't figure out why the new_post_path
will leads to 'edit' path????
Could someone help me with this? If you need more codes plz tell me.
Thank you!
UPDATES
Add the _sidebar.html.erb (sorry for the format, idk how to keep them as original, there are some normal nav
, ul
, li
tags outside)
The new.html.erb
<%= form_for @post do |f| %>
<div class="field">
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.text_area :content, placeholder: "new post here..." %>
</div>
<div class="field">
<%= f.select :public, [['Public', true], ['Private', false]] %>
</div>
<%= f.submit "Post", class: "btn" %>
<% end %>
I tried app.new_post_path
, it shows /posts/new
, i guess it's good.
Upvotes: 3
Views: 18626
Reputation: 5330
You are probably using edit_post_path
in your new.html.erb
for posts.
It is complaining about no route matches
as you haven't passed id of the edit post. But that shouldn't be in new
view in the first place, so you probably need to delete that line - for editing post
Upvotes: 7