【发布时间】:2015-11-14 22:03:19
【问题描述】:
我有一个 rails 4 应用程序。
在与另一个模型有belongs_to关联的控制器中创建允许的参数时,您是否需要在允许的参数中包含外键,以便在保存记录时可以更新它,还是自动更新?
【问题讨论】:
-
你应该允许它,除非你使用嵌套表单
标签: ruby-on-rails foreign-keys strong-parameters
我有一个 rails 4 应用程序。
在与另一个模型有belongs_to关联的控制器中创建允许的参数时,您是否需要在允许的参数中包含外键,以便在保存记录时可以更新它,还是自动更新?
【问题讨论】:
标签: ruby-on-rails foreign-keys strong-parameters
它不是自动的。
在 Rails 4 中,您必须允许该属性才能批量分配其值。另一个模型的外键是您尝试更新的当前模型的属性。不允许这样做,你不能更新它的值。
【讨论】:
外键不是自动的,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
这应该让您对您可以对您的对象做什么有一些看法。
更新
如果你想每次都给当前用户分配一个帖子,你可以使用以下方法:
#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
【讨论】:
x_id,你必须允许它的参数。如果你想填充关联的对象(IE 人不能改变它),你可以像上面那样做
user_id 时才需要这些参数。