Sunday, 15 September 2013

Ruby on Rails: Form routes to a different URL

Ruby on Rails: Form routes to a different URL

I have a form that saves data, but it gets routed to the wrong URL.
If my form is in
localhost:3000/users/1/styles/1
And when I submit the form, I get redirected to this:
localhost:3000/styles/1
and then I get an error:
Couldn't find User without an ID
views/comments/_form.html.erb
<%= form_for [@commentable, @comment] do |f| %>
<%= f.text_area :content, rows: 3 %>
<%= f.submit %>
<% end %>
styles_controller.rb
def show
@user = User.find(params[:user_id])
@style = @user.styles.find(params[:id])
@commentable = @style
@comments = @commentable.comments
@comment = Comment.new
end
comments_controller.rb
before_filter :get_commentable
def new
@comment = @commentable.comments.new
end
def create
@comment = @commentable.comments.new(params[:comment])
@comment.user = current_user
if @comment.save
redirect_to @commentable, notice: "Comment created."
else
render :new
end
end
private
def get_commentable
@commentable =
params[:commentable].classify.constantize.find(commentable_id)
end
def commentable_id
params[(params[:commentable].singularize + "_id").to_sym]
end
routes.rb
resources :styles do
resources :comments, :defaults => { :commentable => 'style' }
end
Please let me know if there's other information that is needed. Why am I
getting rerouted to a different url? My comment does save into my
database.
Thank you

No comments:

Post a Comment