Rails 如何限制属性更新

克莱姆尼

我得到了一个 Object, Rating,有 2 个字段,user_idvalue

class CreateRatings < ActiveRecord::Migration[5.1]
     def change
       create_table :ratings do |t|
          t.belongs_to :user
          t.integer :user_id
          t.decimal :value
       end
     end
end

在创建时,我想将 user_id 和 value 设置为 Controller 中的给定值:

@rating = Rating.create(user_id: 1, value: 2)

但是在我创建它之后,应该不可能更改user_id 属性只是value 属性所以在那之后:

@rating.update(user_id: 2, value: 3)

@rating.user_id 仍应返回 1,但值应为 3。

我的想法是使用before_update来恢复更改,但这对我来说并不合适。

是另一种方法吗?

我希望我能更清楚我的问题是什么..

谢谢

更新

控制器看起来像这样:

  def create
     Rating.create(rating_params)
  end

   def edit
     Rating.find(params[:id]).update(rating_params)
   end

   private

   def rating_params
      params.require(:rating).permit(:user_id, :value)
   end
塞尔吉奥·图伦采夫

你可以用一些 strong_params 来做到这一点。user_id更新时根本不允许沿着这些路线的东西:

class RatingsController
  def create
    @rating = Rating.create(create_rating_params)
    ...
  end

  def update
    @rating = Rating.find(params[:id])
    @rating.update_attributes(update_rating_params)
    ...
  end

  private

  def create_rating_params
    params.require(:rating).permit(:user_id, :value)
  end

  def update_rating_params
    params.require(:rating).permit(:value)
  end
end

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章