Copy rails association in 2.3 with clone method

I have a Reminder model, Attachment Model and it has habtm relationship
with each other.

So I have a created another table as attachment_reminders table in mysql
through migrations and it has reminder_id and attachment_id fields.

In controller I need to copy a record in attachment table and save it in
Attachment table. I am able to do that…

But I need to add the same in the attachment_reminders table also. How
can I achieve it. Please find my code below

def view_reminder
    @reminder = Reminder.find(params[:id2])
    @attachments = @reminder.attachments
       if request.post?
         Reminder.create(:sender=>@reminder.user_id,:recipient=>params[:recipient],:body=>params[:body])
         @attachments.each do |at|
         rec = at.clone
         rec.created_at = Time.now
         rec.updated_at = Time.now
         rec.save
      end
    flash[:notice]="Reminder updated successfully"
    redirect_to :controller=>"reminde", :action=>"view_reminder",

:id2=>params[:id2]
end

On Oct 11, 2013, at 3:17 AM, ruby rails wrote:

I have a Reminder model, Attachment Model and it has habtm relationship
with each other.

So I have a created another table as attachment_reminders table in mysql

Is this a copy-paste error? s/b attachments_reminders (both plural),
right?

through migrations and it has reminder_id and attachment_id fields.

In controller I need to copy a record in attachment table and save it in
Attachment table. I am able to do that…

But I need to add the same in the attachment_reminders table also. How

You should never worry about the attachments_reminders table directly at
all. If you add attachments to the @reminder.attachments collection,
when you save the @reminder, the attachments will be “attached”
automagically. The inverse is also true. You can create new attachments
on the reminder by calling @reminder.attachments.build( any arguments
here ).

        rec.updated_at = Time.now

Nothing in this loop is needed. If you have properly defined your habtm
relationship (including correctly-named table) then nothing about this
has to be declared like this. You don’t need to test for post?, you
don’t need to do anything besides create or update the main object in
your controller, just as if it didn’t have any attachments. When you
save the main object, all of its related objects are created, updated,
saved – whatever they need.

        rec.save
     end
   flash[:notice]="Reminder updated successfully"
   redirect_to :controller=>"reminde", :action=>"view_reminder",

:id2=>params[:id2]
end

Walter

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs