Rails 3 を使用しています。attr_accessible :rating, :review, :user
当然、 を宣言する必要はありませんが、そうしないと、レビュー フォームはエラー を返します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 %>