routing - Unable to create posts in rails forum on the topics page -
i new rails , trying create forum. forum has many topics, topics belong forum , have many microposts, , microposts belong both topics , users. however, no matter try, posts not created. when try post, routing error "no route matches [get] "/topics""
my routes.rb file:
resources :users resources :sessions, only: [:new, :create, :destroy] resources :microposts, only: [:create, :destroy] resources :forums, only: [:index, :show] resources :topics, only: [:show]
_micropost_form.html.erb
<%= form_for(@micropost) |f| %> <%= render 'shared/error_messages', object: f.object %> <div class="field"> <%= f.hidden_field :topic_id, value: @topic.id %> <%= f.hidden_field :user_id, value: current_user.id %> <%= f.text_field :summary, placeholder: "one-line summary..." %> <%= f.text_area :content, placeholder: "compose new post..." %> </div> <%= f.submit "post", class: "btn btn-large btn-primary" %> <% end %>
microposts_controller.rb
class micropostscontroller < applicationcontroller before_action :signed_in_user, only: [:create, :destroy] before_action :correct_user, only: :destroy def create #@topic = topic.find_by_id(params[:topic_id]) @micropost = current_user.microposts.build(micropost_params) if @micropost.save flash[:success] = "your solution has been posted!" redirect_to topic_path(@topic) else redirect_to topic_path(@topic) end end def destroy @micropost.destroy redirect_to root_url end private def micropost_params params.require(:micropost).permit(:summary, :content, :user_id) end def correct_user @micropost = current_user.microposts.find_by(id: params[:id]) redirect_to root_url if @micropost.nil? end end
as can see, commented out first line in create function because i've tried posting based on the micropost's relationship topic no avail. in advance , let me know if if posted more code!
in :topics
resource, didn't defined index method, that's why won't able topic's list or index page. try change route this:
resources :topics, only: [:index, :show]
or remove attribute resources, automatically include methods default.
resources :topics
also if have relationship between models, should define nested routes in routes file, example, can define them this, can change them accordingly:
try change route file this:
resources :users resources :sessions, only: [:new, :create, :destroy] resources :forums resources :topics resources :microposts, only: [:new, :create, :destroy] end end
in above case, can access forums this:
http://localhost:3000/forums
you can access topics this:
http://localhost:3000/forums/id/topics
you can access microposts this:
http://localhost:3000/forums/id/topics/id/microposts
if want access /microposts
directly have put outside resource.
resources :microposts, only: [:index]
now able access it:
http://localhost:3000/microposts
hope help. thanks.
Comments
Post a Comment