Rails 3 嵌套资源变量

发布于 2024-11-07 18:37:18 字数 303 浏览 0 评论 0原文

我有一些与我正在创建的 Transaction 对象相关的问题。

交易属于贷款且贷款有很多交易。

因此,我设置了一个嵌套路由:

resources :loans do
  resources :transactions
end

我的问题是:如何将贷款值传递到交易的“loan_id”字段中?这最好在控制器中完成还是作为表单中的隐藏字段完成?嵌套路由是否创建了一种获取此变量的简单方法?

我以为这会自动完成,但当我按原样保存时,该字段为空。

任何帮助将不胜感激!

I have a few questions relating to a Transaction object that I'm creating.

Transaction belongs_to Loan and Loan has_many Transactions.

Therefore, I setup a nested route:

resources :loans do
  resources :transactions
end

My question is: How do I pass the loan value into the Transaction's 'loan_id' field? Is this best done in the controller or as a hidden_field in the form? Does the nested route create an easy way to grab this variable?

I assumed this would be done automatically, but the field is empty when I saved it as-is.

Any help would be greatly appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冰魂雪魄 2024-11-14 18:37:18

如果您调用特定交易,交易的路线将是

loans/:loan_id/transactions/new

您可以使用模型关联,如下所示:在您的create操作中:

@transaction = Loan.find(params[:loan_id]).transactions.build

这样您的新@交易将已经填充有loan_id

if you call a specific transaction, the route for a new transaction will be

loans/:loan_id/transactions/new

you could use model association like this: in your create action:

@transaction = Loan.find(params[:loan_id]).transactions.build

that way your new @transaction will be already populated with the loan_id

蛮可爱 2024-11-14 18:37:18

考虑将 before_filter 添加到您的控制器,并让它调用私有方法来获取所有操作的 :id。将其放在 transactions 控制器的顶部:

before_filter :load_loan

然后在所有操作之后添加:

private
def load_loan
  @loan.find(params[:loan_id])
end

在您的 new 操作中像这样使用它:

@transaction = @loan.transactions.build

Consider adding a before_filter to your controller and having it call a private method to grab the :id across all actions. Place this at the top of your transactions controller:

before_filter :load_loan

And then after all the actions, add:

private
def load_loan
  @loan.find(params[:loan_id])
end

Use it like this in your new action:

@transaction = @loan.transactions.build
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文