在父模型中访问嵌套子属性?

时间:2012-05-04 08:11:20

标签: ruby-on-rails ruby-on-rails-3

我有以下表单可供发布,轨道字段在我的发布模型中被接受为嵌套属性。

<%= form_for(@release) do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id, :class => "text" %>
<%= f.text_field :title, :class => "text" %>

<%= f.fields_for :tracks do |builder| %>
<%= render 'track_fields', :f => builder %>
<% end %>

<% end %>

我的发布模型包含:

  accepts_nested_attributes_for :tracks, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => :true
  accepts_nested_attributes_for :releases_tracks

  before_save :order_tracks
  before_update :order_tracks


  def order_tracks 
    releases_tracks.each { |t| t.position = track_attributes.position }
    tracks.each { |t| t.user_id = user_id}
    tracks.each { |t| t.label_id = label_id}
  end

  def track_attributes=(track_attributes)
    track_attributes.each do |attributes|
    tracks.build(attributes)
    artists_tracks.build(attributes)
    end
  end

一切都运作良好,除了下面的一行,我试图获取在表单的fields_for部分中输入的位置值。我可以访问父表单中的值,例如user_id,但是如何访问子值?

releases_tracks.each { |t| t.position = track_attributes.position }

全部谢谢!

(注意:我不想为此使用acts_as_list)

1 个答案:

答案 0 :(得分:0)

尝试使用:

releases_tracks.each { |t| t.position = track_attributes[:position] }  or 
releases_tracks.each { |t| t.position = track_attributes["position"] }