如何通过Rails 3中的嵌套表单向下传递外键属性

时间:2011-04-28 04:09:38

标签: ruby-on-rails ruby-on-rails-3 foreign-keys foreign-key-relationship nested-forms

我有三种模式:

class Client < ActiveRecord::Base
   has_many :balancesheets
   has_many :investment_assets, :through => :balancesheets

class Balancesheet < ActiveRecord::Base
   belongs_to :client
   has_many :investment_assets, :dependent => :destroy
   accepts_nested_attributes_for :investment_assets, :allow_destroy => true

class InvestmentAsset < ActiveRecord::Base
    belongs_to :balancesheet
       belongs_to :client

我有两个与外键client_id有关的问题。首先,当我创建新的余额表时,我使用collection_select从列表中选择客户端。我宁愿将新的balancesheet链接放在客户端显示页面上,只是将客户端ID传递给表单,这样我就不必从列表中选择客户端或在字段中键入它。首先,我该怎么做?

其次,investment_asset模型嵌套在balancesheet表单中。除了investment_asset的client_id属性为空之外,一切正常。我不知道为什么,因为我的协会似乎没问题。所以问题是,如何通过嵌套表单传递此client_id属性?我可以发布模型或控制器,请告诉我。

更新我已经找到了第一个问题here的答案。但是,我仍然试图找出基于该答案的第二部分,即如何通过嵌套表单传递此client_id?为了说明在创建资产负债表时如何通过用户ID,这里是客户端显示页面链接:

<%= link_to 'New BalanceSheet',new_balancesheet_path(:id => @client.id) %>  

在资产数据表中,我有一个隐藏字段:

 <%= f.hidden_field :client_id %>  

在资产负债表控制器中,这是新动作:

 @balancesheet = Balancesheet.new(:client_id => params[:id])

这很好用。因此对于investment_asset,我使用的是Ryan Bates nested_form gem,它的链接语法略有不同。因此,在资产数据表中,添加新的investment_asset的链接是:

 <%= f.link_to_add "Add asset", :investment_assets %>

我无法弄清楚如何通过以下方式传递用户ID:

(:id => @client.id)

我可以在invest_asset控制器中的新操作中添加相同的内容并添加隐藏字段,但我不确定如何在链接上传递它。想法?

1 个答案:

答案 0 :(得分:0)

对于我所知道的一切来说,这可能是完全黑客攻击,但我所知道的只是非常有限。我最终在这里做的是用户jQuery从资产负债表中获取id并强制它进入invest_asset的隐藏字段。 jQuery:

// get the value from the balancesheet hidden field that contains the user_id value
var balsheetclientid = jQuery('#hiddenid').attr('value'); 
// insert it into the value attribute in the hidden field with class name .iaclientid
jQuery('.iaclientid').val(balsheetclientid) 

然后我的隐藏字段看起来像这样:

<%= f.hidden_field :client_id, :class => 'iaclientid', :value => '' %> 

它运作得很好。希望这是一种有效的方法。