\" association that is created on \".build\"?" />
开发者

Access join-model on .build with has_many, :through

开发者 https://www.devze.com 2023-03-22 03:22 出处:网络
Is there any way to access the join model of a \"has_many, :through =>\" association that is created on \".build\"?

Is there any way to access the join model of a "has_many, :through =>" association that is created on ".build"?

I'm sorry that I don't have the actual code here, but I hope you understand what I want ;)

a:
has_many :bs
has_many :cs, :through => :bs

b and c are defined correctly (w/ belongs_to, has_many, has_many-through)

Now: In a controller I'm trying to do a

var = @a.cs.build

(within a transaction, but I don't think that's relevant here),which "creates" a c-instance and also the joining b. But how can I access the automatically created b, as I'd like to pass some attributes? Is that possible at all, or do I have to work around with

@a.create_c 
# or
varb = B.new
varb.someattr1 = "foo" # <- this is what I want w/ .build
varb.someattr2 = "bar"
varb.a = @a
varc = C.开发者_如何学Pythonnew
varc.someattr3 = "asdf"
varb.c = varc
# ... and some .save! 

or sth like that? I don't think that's very good style, nor does it 'break' the wrapping transaction for some reason

I rly hope that you get what I want.


EDIT

Umh, first of all: thanks for your answers, but I'm still stuck. I'll try to be more precise:

@a = A.new
@a.name = "foo"
varc = @a.cs.build
varc.name = "bar"
@a.save!

That's gonna give me one instance of A,B and C. How can I set an attribute for B?

sth. like:

varb = join_model_of(@a, varc)
varb.name = "foobar"

before the @a.save!

TYIA!


When you do

var = @a.cs.build

it actually gives you the bs object and so you can access the attributes of bs object using var.
You can try it yourself.


I'm confused a bit about your question, but I do know that given Model01, JoinModel and Model02 you should have accessors like this:

model1.model2s
model1.model2_ids
model1.join_models
model1.join_model_ids

That last two will give you what I think you are asking for...if I'm wrong can you explain so that an idiot like me can understand?

thanks!


Solution:

varb = @a.bs.build
varc = varb.build_c
varb.someattr1 = "foo"
varb.someattr2 = "bar"
varc.someattr3 = "sadf"
@a.save!

[ BUT: (haven't spent much thinking on the "why") My class B does include:

validates_presence_of :a # <- problem!
validates_presence_of :c

I can't get past the first (of the above) validation. I have to comment it out, yet it gets written into the DB (correctly). ]

At least this works. Yet I'm not 100% sure if this is the way you should do it. Pls Cmt!

0

精彩评论

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