form_for, need to modify the :url based on if it is persisted or not

My have a form in a partial like this:

form_for @article, :url => articles_path, …

Now currently it posts to the create action.

I want it to post to comment_article_path under certain conditions, how can I do this?

Can I put in a expression like:

@article.persisted? comment_article_path : articles_path

Is this good practice?

It can certainly be done easy enough, but I’d question the problem you are trying to solve if you want to do something like that.

You can create a helper method (in helpers/articles_helper.rb):
def correct_post_path
    @article.persisted? comment_article_path : articles_path
end

And then use this helper in your form builder
  form_for @article, correct_post_path do ... end

That helps ? Maybe you can tell us under what conditions you need to
change post url, maybe you over-engineer somewhere...

Thanks.

When you add something to a helper like articles_helper, does it have the request object in there also?

How does it get the @articles object when I call it like:

form_for @article, correct_post_path, …

I would have though it would be:

form_for @article, correct_post_path(@article), …

Thanks.

When you add something to a helper like articles_helper, does it have the request object in there also?

How does it get the @articles object when I call it like:

Controller instance variables are copied across to the view object so that just works (although you can of course pass parameters into your helpers explicitly)

Fred