0

使用 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 %>
4

3 回答 3

0

您应该使 :rating 和 :review 可访问。为什么需要使用户可访问?如果您只是想保存用户的评论(当然是在他登录时),那么您可以从控制器传入用户的 id,我看到您在 create 方法中已经完成了。

如果您还有其他想要实现的目标,请告诉我。

于 2012-09-15T17:07:27.007 回答
0

使用assign_attributes 通过传入属性哈希来设置特定批量分配安全角色的所有属性

user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true })
于 2012-09-15T18:07:59.000 回答
0

关于这个问题,我通过发布以下内容进行了修复:

class ReviewsController < ApplicationController
  ...

  def create
    @review = @reviewable.reviews.new(params[:review])
    @review.user_id = current_user.id
    ...
  end
end

通过这样做,user模型不需要被声明为可批量赋值的。

于 2012-09-16T12:17:44.463 回答