Forum: Ruby on Rails simple attribute copy

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Sarah Jackson (Guest)
on 2007-04-25 23:43
Lol don't ask why but I would like to use to code I found on the forum
to copy two values from table A to table B.  It looks a bit roundabout
but it doesn't matter to me.


Okay so I know that this part goes in the controller class(i dont think
I have to modify it at all?):

def copy_attributes(dest, src, *attrs)
  for attr in attrs
    dest.send(attr.to_s + '=',src.send(attr))
  end
end


Then where does this line of code go/how do I execute the copy?  Would I
include it in def new, or between the "ends" in the above code, or wrap
it in <=% %> tags in the view.

copy_attributes(bidule, biniou, :foo, :bar, :baz)
Sarah Jackson (Guest)
on 2007-05-04 20:57
Hey I just decided to start tackling this one again.    Can anybody
point me in the right direction?

Sarah Jackson wrote:
> Lol don't ask why but I would like to use to code I found on the forum
> to copy two values from table A to table B.  It looks a bit roundabout
> but it doesn't matter to me.
>
>
> Okay so I know that this part goes in the controller class(i dont think
> I have to modify it at all?):
>
> def copy_attributes(dest, src, *attrs)
>   for attr in attrs
>     dest.send(attr.to_s + '=',src.send(attr))
>   end
> end
>
>
> Then where does this line of code go/how do I execute the copy?  Would I
> include it in def new, or between the "ends" in the above code, or wrap
> it in <=% %> tags in the view.
>
> copy_attributes(bidule, biniou, :foo, :bar, :baz)
James S. (Guest)
on 2007-05-04 21:14
(Received via mailing list)
On May 4, 2007, at 12:57 PM, Sarah Jackson wrote:
>>
>>
>> Then where does this line of code go/how do I execute the copy?
>> Would I
>> include it in def new, or between the "ends" in the above code, or
>> wrap
>> it in <=% %> tags in the view.
>>
>> copy_attributes(bidule, biniou, :foo, :bar, :baz)

You definitely shouldn't be changing models in the view.

Depending on what you're trying to do, you might be better off
putting your attribute copying code in your model, along the lines of:

class ModelA < ActiveRecord::Base
end

class ModelB < ActiveRecord::Base

  def self.create_from_a(model_a)
    # Set this model's attributes from other model's attributes
    save
  end
end

Then in your controller you can call:

class MyController < Application
  def my_action
    @my_a = ModelA.find(params[:id])
    @my_b = ModelB.create_from_a(@my_a)
  end
end


James.

--
James S.
http://jystewart,net/process/
This topic is locked and can not be replied to.