Ci. wrote:
Hi everybody,
here is my problem.
I have a Post model, a Tag model, and they are related to each other
by an has_and_belongs_to_many relationship.
Now I run ./script/console:
p=Post.new
p.title=“Hello”
p.save
t=Tag.new
t.name=“tag1”
p.tags = [t]
The result is that a Post record is created and saved, and then also a
Tag record is created and saved, together with a record in the join
table posts_tags.
The question is: why are the tag and the record in the join table
saved? Shouldn’t they wait for an explicit save?
To be more clear, why the last line ( p.tags=[t] ) triggers the
creation in the database of a record in the tags table and another in
the posts_tags table? Is there a way from stopping this until an
explicit save
occurs?
I hope someone can answer my question, I’m quite a rails newbie so I
need help. Thanks.
Er… I’ve got something useful,I’ll take it in an example
first,I create two table Posts & Tags,and association table
Posts_Tags,and habtm assciation in models
then,script/console,one command followed by the data table
p = Post.new
=> #<Post:0x3477af4 @new_record=true, @attributes={“sth”=>nil}>
p.save
=> true
t = Tag.new
=> #<Tag:0x3460fc0 @new_record=true, @attributes={“sth”=>nil}>
t.save
=> true
p.tags.send(“load_target”)
=> []
p.tags.target << t
=> [#<Tag:0x3460fc0 @new_record=false,
@errors=#<ActiveRecord::Errors:0x345eb30 @errors={},
@base=#<Tag:0x3460fc0 …>>, @attributes={“id”=>1, “sth”=>nil},
@new_record_before_save=true>]
and the data table …
mysql> select * from posts_tags;
Empty set (0.01 sec)
and the model …
y p.tags
so , i got it ,i separate model association from data table[bad ENGLISH
i know … ]
when you want to save the associations , following is the answer
p.tags.send(“insert_record”,t)
=> true
and the data table …
mysql> select * from posts_tags;
±—±--------±-------+
| id | post_id | tag_id |
±—±--------±-------+
| 1 | 1 | 1 |
±—±--------±-------+
1 row in set (0.00 sec)
SO , I GOT IT, didn’t I?
hehe , I read the source code and hope this will help you too.
Please give me your MSN,I wanna a coder friend[bad english,i know…]
PS, transaction block is recommended from the source code,in this
example…
p.transaction do
Er …
end
^^