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 ).

> 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

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

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/5DE3D776-99C7-41EE-B727-F7E99160F5AB%40wdstudio.com.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to