使用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 %>
答案 0 :(得分:0)
您应该:评分和:评论可访问。为什么需要让用户可以访问?如果您只是想保存用户的评论(当然,当他登录时),那么您可以从控制器传递用户的ID,我看到您在create方法中已完成。
如果你想要实现其他目标,请告诉我。
答案 1 :(得分:0)
使用assign_attributes通过传入属性哈希来设置特定质量分配安全角色的所有属性
user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true })
答案 2 :(得分:0)
参考这个question,我通过发出以下内容来修复:
class ReviewsController < ApplicationController
...
def create
@review = @reviewable.reviews.new(params[:review])
@review.user_id = current_user.id
...
end
end
通过这样做,user
模型不需要声明为可批量分配。