2011-04-21 32 views
2

我是一個stackoverflow新手。請仁慈;-)Rails accept_nested_attributes_for更新/插入的孩子的返回值

我有一個簡單的has_many關聯accept_nested_attributes_for。一切正常。但我真正需要的是更新和/或插入的孩子的返回值,因爲我發送每個Ajax的表單,並且在成功發佈/放置後只需要操作這些孩子的表單字段。

編輯:

型號:

class Pirate < ActiveRecord::Base 
    has_many :ships 
    accepts_nested_attributes_for :ships, :reject_if => proc { |a| a[:name].blank? }, :allow_destroy => true 
end 

class Ship < ActiveRecord::Base 
    belongs_to :pirate 
end 

控制器:

def new 
    @pirate = Pirate.new 
    4.times { @pirate.ships.build } 
end 

def edit 
    @pirate = Pirate.find(params[:id]) 
end 

def create 
    @pirate = Pirate.new(params[:pirate]) 

    respond_to do |format| 
    if @pirate.save 
     format.js 
    else 
     format.js 
    end 
    end 
end 

def update 
    @pirate = Pirate.find(params[:id]) 

    respond_to do |format| 
    if @pirate.update_attributes(params[:pirate]) 
     format.js 
    else 
     format.js 
    end 
    end 
end 

查看:

<%= form_for @pirate, :remote => true do |f| %> 
    <%= f.label :name, "Pirates Name" %> 
    <%= f.text_field :name %> 

    <%= f.fields_for :ships do |ship| %> 
    < 
    <%= f.label :name, "Ship Name" %> 
    <%= ship.text_field :name %> 
    <% end %> 

    <%= f.submit %> 
<% end %> 

update.js.erb:

<% @pirate.only_updated_ships.each do |u| %> 
    alert("<%= u.id %>"); 
    do something... 
<% end %> 

<% @pirate.only_newly_inserted_ships.each do |i| %> 
    alert("<%= i.id %>"); 
    do something... 
<% end %> 

所以,我這裏有一個遠程調用和create.js.erb和update.js.erb,我想返回的更新和/或插入的子對象的工作。

問題是,您只能獲得@pirate作爲成功的post/put的返回值。並且打電話給@ pirate.children當然會給你所有的孩子。

希望我的問題現在更清楚了嗎?

+0

添加了一個更新我的帖子 – 2011-04-21 11:13:15

回答

2

對此有幫助嗎?

u = User.first 
u.login #=> 'hello' 
params[:user] #=> { :login => 'world' } 
u.attributes = params[:user] 
u.login #=> 'world'. Other attributes are the same as before 
u.changed #=> ["login"] 

這只是有些很難給出直接的答案,除非你告訴我們一些代碼;)

UPDATE:

不知道它去上班,但值得一試: 嘗試@pirate.attributes = params[:pirate]而不是@pirate.update_attributes(params[:pirate]) 然後,

@only_updated_ships = @pirate.ships.find_all { |ship| ship.changed? } 
@only_updated_ships.each { |ship| ship.save } 
+0

我甲肝e更新了我的問題。 stackoverflow非常酷;-)。無論如何,我認爲髒跟蹤在這裏不起作用,即使用於兒童屬性,或者我錯了嗎? – Xiaolong 2011-04-21 10:57:47

+0

Merci !!它像一個魅力!保存了我的一天。我接受了你的回答,但我還是不能投票,對不起,夥計! – Xiaolong 2011-04-21 11:30:09

+0

當然,呃​​,很高興它幫助;) – 2011-04-21 11:32:17