使用 Rails 3。按道理,我不应该需要声明attr_accessible :rating, :review, :user
,但如果我不这样做,评论表单会返回 error Can't mass-assign protected attributes error :rating, :review, :user
。:user
出于安全原因,我不想公开全部内容。我做错了什么?
# review.rb
class Review < ActiveRecord::Base
belongs_to :reviewable, :polymorphic => true, :counter_cache => true
belongs_to :user, :counter_cache => true
attr_accessible :rating, :review, :user
validates :review, :presence => true, :length => { :minimum => 2, :maximum => 500 }
validates :rating, :inclusion => { :in => ApplicationConstants::RATINGS.collect(&:first) }
end
# reviews_controller.rb
class ReviewsController < ApplicationController
before_filter :find_reviewable
def create
@review = @reviewable.reviews.new(params[:review].merge(:user => current_user))
if @review.save
flash[:success] = 'Thanks for adding your review.'
redirect_to @reviewable
else
flash[:error] = 'Error, try again.'
redirect_to @reviewable
end
end
...
private
def find_reviewable
resource, id = request.path.split('/')[1, 2]
@reviewable = resource.singularize.classify.constantize.find(id)
end
end
# user.rb
class User < ActiveRecord::Base
has_many :reviews, :as => :reviewable
end
# reviews/_form.html.erb
<%= form_for [@reviewable, @review] do |f| %>
<div id="rating_buttons" class="btn-group" data-toggle-name="review[rating]" data-toggle="buttons-radio">
<% ApplicationConstants::RATINGS.each do |rating| %>
<button type="button" class="btn<%= active(@review.rating, rating[0]) %>" value="<%= rating[0] %>"><%= rating[1] %></button>
<% end %>
</div>
<%= f.hidden_field :rating %>
<%= f.text_area :review, :class => 'input-xxlarge', :rows => '3' %><br>
<%= f.submit 'Submit', :class => 'btn btn-primary' %>
<% end %>