问题
My route file looks like this:
scope :locslug/:userslug do
....
....
post 'rate/:stars' => 'articles#rate' :as => :rate_article
end
I'm trying to generate a form with an action that targets the rate action in articles. Ideally, when the form is submitted, a rating will either be created or updated. Elsewhere, I have that an article has_many ratings.
This doesn't work:
= form_tag rate_article_path, :method=>'post', :id => "rate_article" do
=hidden_field_tag :article_id, @article.id
=hidden_field_tag :stars, 0
=hiden_field_tag :user, current_user.id
Help is very much appreciated. Thank you.
回答1:
does rails shows some error? I think you have your route wrong: 'rate/:stars' tells rails to expect a parameter when you call rate_article_path (something link rate_article_path(5) for 5 stars)
you should have your route:
post 'rate/:article_id' => 'articles#rate' :as => :rate_article
your form:
= form_tag rate_article_path(@article), :method=>'post', :id => "rate_article" do
=hidden_field_tag :stars, 0
now on your controller
def rate
article = Article.find(params[:article_id])
article.rates.create(:user => current_user, :stars => params[:stars])
end
(it's really simplified, you should do some validations, it's just to get the idea of what to do)
来源:https://stackoverflow.com/questions/11304766/form-tag-for-create-update-action-rails-3