Ruby on Rails Thursday, September 5, 2013

On Sep 5, 2013, at 11:50 AM, Scott Ribe wrote:

> On Sep 5, 2013, at 9:47 AM, honey ruby <emailtohoneyruby@gmail.com> wrote:
>
>> Hi all
>>
>> I have two tables A and B
>> I have saved a record in table A and I want to save the id of that record in table B. How Can I do that.
>> Well I can do by search of same params which I save in Table A but I feel it is not that good approach.
>
> Just save it, then use the id ;-)
>
> Seriously, this is a very common idiom, and you'll find that rails takes care of it.
>

You may need to reload the object, as in

if @whatever.save
@whatever.reload
@another_thing.whatever_id = @whatever.id
@another_thing.save
end

That would only be true in a create method, because the ID isn't known until after the thing is saved. But if your relationships are declared in the usual way (has_many, belongs_to, etc.) then this plumbing is taken care of for you in most cases.

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+unsubscribe@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/AB2F082D-434A-40A3-BD64-5B23B05B2761%40wdstudio.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment