【发布时间】:2015-02-06 17:44:26
【问题描述】:
导轨 4
我有一个帐户和注释模型。我正在尝试保存与该帐户相关的注释。
笔记模型
class Note < ActiveRecord::Base
belongs_to :account
end
帐户模型
class Account < ActiveRecord::Base
...
has_mamy :notes
end
路线:
resources :accounts
resources :notes
get 'accounts/:id/new_note' => 'notes#new'
notes_controller.rb
def new
@note = Note.new
@note.account_id = params[:id]
respond_with(@note)
end
def create
@note = Note.new(note_params)
@note.save
repond_with(@note)
end
private
def note_params
params.require(:note).permit(:title, :description, :account_id, :opportunity_id, :created_by, :updated_by)
end
end
当我 GET ".../accounts/1/new_note" 并 POST 请求时,注释会被保存,但 @note.account_id = nil。
为什么?
在我的其他模型机会中,具有类似的行为并且一切正常。
【问题讨论】:
-
您确定您不是在寻找
@note.account_id = params[:account_id]吗?为什么您使用自定义路由而不是嵌套资源? -
我真的不知道嵌套资源。我会试一试。但我想了解为什么这种方式不适用于笔记。它应该是 params[:id] 而不是 params[:account_id] 因为这是我在 Route.rb 上声明它的方式据我了解,如果我更改为您提出的解决方案 @note.account_id = params[:account_id ] 我的路线应该看起来像这样 get 'accounts/:account_id/new_note' 我刚刚尝试过但也不起作用
-
这对我来说似乎有点混乱。您如何执行 POST 请求?在您发布的路线中,没有任何内容涉及定义您的方法的 notes_controller.rb。
-
POST 是通过标准 POST /notes notes#create 完成的。也许我忘了澄清有资源:notes
-
所以我假设您的帐户控制器中有
new_note操作?那是什么样子的?也许您希望 accounts_controller.rb 中的new_note操作看起来像 notes_controller 中的new操作?
标签: ruby-on-rails ruby-on-rails-4 routes params