一个控制器有多个型号?我这样做了吗?

din*_*ing 5 ruby-on-rails

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

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

因此,财务选项卡基本上可以处理来自两个模型的数据:交易和bank_accounts.我我应该制作模型(交易和bank_accounts)然后制作一个名为Financials的控制器,然后我可以从Financials控制器查询模型并在app/views/financials /中显示页面

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

谢谢!

Shr*_*hna 4

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

交易: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
Run Code Online (Sandbox Code Playgroud)

在您的bank_account模型中,添加以下内容:

class Bank_account < ActiveRecord::Base
  belongs_to :financial
end
Run Code Online (Sandbox Code Playgroud)

在您的财务模型中添加以下内容:

class Financial < ActiveRecord::Base
  has_many :transactions
  has_many :bank_accounts
end
Run Code Online (Sandbox Code Playgroud)

现在,从您的财务控制器中,您可以使用如下内容:

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
Run Code Online (Sandbox Code Playgroud)

在您看来,您可以通过执行以下操作来查看属于特定财务的所有银行账户:

<% @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 -%>
Run Code Online (Sandbox Code Playgroud)

在您的视图中,您可以通过添加类似的内容来查看属于特定财务的所有交易:

<% @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 -%>
Run Code Online (Sandbox Code Playgroud)

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