我知道,@pin
在create
方法正确的语法是新方法中@pin的正确语法是什么?
@pin = current_user.pins.build(pin_params)
,但我只是不能100%确定在new
方法要使用的语法,因为它只是初始化。
是吗?
def new
@pin = Pin.new
end
还是它?
def new
@pin = current_user.pins.build
end
我知道,@pin
在create
方法正确的语法是新方法中@pin的正确语法是什么?
@pin = current_user.pins.build(pin_params)
,但我只是不能100%确定在new
方法要使用的语法,因为它只是初始化。
是吗?
def new
@pin = Pin.new
end
还是它?
def new
@pin = current_user.pins.build
end
使用第二个,因为它会设置USER_ID自动
这取决于您是否会在表单中使用@pin.user
变量?
也许你可以使用你的表格@pin.user.name
。 常见的错误模式是为user_id
列创建hidden_field
列,因为它不安全。
两者都可以使用。没有最佳做法(至少我不知道)为此。 这更多的是一个偏好问题。我会选择以前的变体,因为它对我来说更容易阅读。
但是请注意,两行的结果是不同的。 第二行equvalient到:
Pin.new(user: current_user)
我相信,在你的代码中的错误。它应该是'@pin = current_user.pins.create(pin_params)' –
不是。它应该是'.build' – boholdyjeramae
构建不会在数据库中创建记录 –