gpt4 book ai didi

ruby-on-rails - 一个 Controller 有多个模型?我这样做正确吗?

转载 作者:行者123 更新时间:2023-12-04 06:10:50 25 4
gpt4 key购买 nike

到目前为止,我的网络应用程序一直相当简单。我有用户、联系人、约会和其他一些需要管理的东西。所有这些都很简单 - 每个部分只有一个模型,所以我只是为每个模型做了一个脚手架,然后修改了脚手架代码以满足我的需要。挺容易...

不幸的是,我在下一节遇到了问题,因为我希望我的应用程序的“财务”部分比我简单搭建的其他部分更深入。例如,当用户单击导航栏上的“联系人”链接时,它只显示一个联系人列表,非常直接并且与脚手架一致。但是,当用户单击导航栏上的“财务”链接时,我想在页面左侧显示银行帐户,在右侧显示一些交易。

所以财务选项卡基本上可以处理来自两个模型的数据:交易和银行账户。我想我应该制作模型(交易和银行账户),然后制作一个名为 Financials 的 Controller ,然后我可以从 Financials Controller 查询模型并在 app/views/financials/中显示页面

我在这个应用程序布局中正确吗?我从来没有接触过脚手架的基础知识,所以我想确保我做对了!

谢谢!

最佳答案

如果您对脚手架感到满意,那么我建议您为两者生成一个脚手架

交易:script/generate scaffold transaction financial_id:integer ...
银行账户:script/generate scaffold bank_account financial_id:integer ...
和财务 script/generate scaffold financials ...
在您的交易模型中,添加以下内容:

class Transaction < ActiveRecord::Base
belongs_to :financial
end

在您的 bank_account 模型中,添加以下内容:
class Bank_account < ActiveRecord::Base
belongs_to :financial
end

在您的财务模型中,添加以下内容:
class Financial < ActiveRecord::Base
has_many :transactions
has_many :bank_accounts
end

现在从您的财务 Controller ,您可以使用以下内容:
def index
@financial = Financial.find(params[:id])

#This fetches all bank_accounts related to financial
@bank_accounts = @financial.bank_accounts

#This fetches all transactions related to financial
@transactions = @financial.transactions
end

在您的 View 中,您只需执行以下操作即可查看属于特定财务的所有银行账户:
<% @bank_accounts.each do |bank_account| -%>
<%=h bank_account.something_here %> <!-- something_here is the column name corresponding to your bank_account table. -->
<%=h bank_account.something_here %> <!-- something_here is the column name corresponding to your bank_account table. -->
<%=h bank_account.something_here %> <!-- something_here is the column name corresponding to your bank_account table. -->
.
.
.
<% end -%>

在您的 View 中,您可以通过添加类似的内容来查看属于特定财务的所有交易:
<% @transactions.each do |transaction| -%>
<%=h transaction.something_here %> <!-- something_here is the column name corresponding to your bank_account table. -->
<%=h transaction.something_here %> <!-- something_here is the column name corresponding to your bank_account table. -->
<%=h transaction.something_here %> <!-- something_here is the column name corresponding to your bank_account table. -->
.
.
.
<% end -%>

请记住,在创建新交易/银行帐户时,请使用属于特定财务的 ID。希望这可以帮助。干杯! :)

关于ruby-on-rails - 一个 Controller 有多个模型?我这样做正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3028892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com