Rails 4 - 强参数 - 白标外键

Rails 4 - Strong Params - white labelling foreign key

我有一个 rails 4 应用程序。

在与另一个模型有 belongs_to 关联的控制器中创建允许的参数时,是否需要在允许的参数中包含外键,以便在保存记录时更新它,还是自动的?

不是自动的。

在Rails4中,您必须允许该属性才能批量分配其值。另一个模型的外键是您要更新的当前模型的属性。未经允许,您无法更新它的值。

外键不是自动的,the associated object is:

这意味着以下内容为真:

#app/controllers/your_controller.rb
class YourController < ApplicationController
   def create
      @item = Item.new new_params
      @associated = Associated.find x

      @item.associated = @associated #-> this always works & will save 
      @item.save
   end

   private

   def new_params
      params.require(:item).permit(:name, :etc) #-> foreign_key would have to be explicitly defined here if associated_id was passed from a form
   end
end

这应该让您对可以使用对象做什么有所了解。


更新

如果你想每次都分配一个post给当前用户,你可以使用以下方法:

#app/controllers/posts_controller.rb
class PostsController < ApplicationController
   def create
      @post = Post.new post_params
      @post.user = current_user # -> however you identify the user
      @post.save
   end
end