开发者

Rails accepts_nested_attributes_for return values for updated/inserted children

开发者 https://www.devze.com 2023-02-28 00:53 出处:网络
I\'am a stackoverflow newbie. Please be merciful ;-) I h开发者_如何学JAVAave a simple has_many association with accepts_nested_attributes_for. Everything works fine. But I what I really need are the

I'am a stackoverflow newbie. Please be merciful ;-)

I h开发者_如何学JAVAave a simple has_many association with accepts_nested_attributes_for. Everything works fine. But I what I really need are the return values for the updated and/or inserted children, because I send the form per Ajax and need to manipulate only these children's form fields after successfully post/put.

EDIT:

Models:

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

Controller:

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

View:

<%= 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 %>

So, I have a remote call here and a create.js.erb and update.js.erb where I want to work with the returned updated and/or inserted children objects.

The problem is that you only get the @pirate as a return value for the successful post/put. And calling @pirate.children will give you of course all children.

Hope my problem is clearer now?


does this help?

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"]

It's just somewhat difficult to give a straight answer unless you show us some code ;)

UPDATE:

Not sure if it's going to work, but it worth trying: try @pirate.attributes = params[:pirate] instead of @pirate.update_attributes(params[:pirate]) then,

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

精彩评论

暂无评论...
验证码 换一张
取 消