![](/img/trans.png)
[英]Ruby on rails: create action doesn't work, while new, edit and update (the same form as in create !) actions works - why?
[英]rails why model new().save doesn't work in create action
在Model-1支架創建動作中,
def create
@auclub = Auclub.new(auclub_params)
user = User.find(current_user.id)
respond_to do |format|
if @auclub.save && user.update(auclub_id: @auclub.id)
format.html { redirect_to @auclub, notice: 'Auclub was successfully created.' }
format.json { render :show, status: :created, location: @auclub }
else
//some codes
end
end
end
並且我想與用戶創建俱樂部
此代碼有效,但是如果我這樣使用
user = User.find(current_user.id)
user.new(auclub_id : @auclub.id)
user.save
它不起作用! update和new.save有什么區別?
嘗試:
@auclub = Auclub.new(auclub_params)
@user = User.find(current_user.id)
@auclub.save
@user.auclub_id = @auclub.id
@user.save
了解更多APi基座
您做事的方式有誤。
如果沒有模型和其他代碼,我建議這樣做:
user = User.find(current_user.id)
user.auclub_id = @auclub.id
user.save
而且我認為您的案例中沒有new
方法可用於ActiveRecord實例(例如user
。
new
上使用ActiveRecord類來創建一個新的實例,如:
user = User.new
而且,我認為使用update
方法與手動重新分配屬性以及使用save
方法保存對象之間沒有太大區別,但是您必須注意性能,DRY原理和在模型上定義的回調。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.