Validates presence of foreign_key & auto child save

Hi there,

You so you know, I’m fairly new to rails - I still have a lot learn.

For fun I’m trying to create a forum in rails. I have some problems with
the create method of the topic resource. I’ve set up a virtual attribute
called text for topic, to use for mass assignment:

In topics_controller.rb:
@topic =[:topic])

In topic.rb:
def text=(text) => text)

The topic model handles the text-attributes by building a post model
through its association.

This is pretty neat I think! It results in very readable and structured
code. But when I try to save the topic with it gives me the
error that “Posts is invalid”. This is because post.rb includes the
validates_presence_of :topic_id

When the validation are run (just before the topic is actually saved)
rails also validates the children of the topic - that is the post model.
As this post has not yet defined a topic_id its validations fail.

The topic id will not be available until the topic is created in the
database - and the topic will not be created in the database until the
post validates - and the post will not validate until the topic id is

I hope you can see the cycle of dependencies.

If I just remove validates_presence_of :topic_id it works like a charm.
Rails even defines the posts topic id through the association set up
with However, to me it seems like a “dirty” solution to
the problem?

What would you do here? Any recommendations/ideas?

Thanks in advance.

Rasmus N. wrote:

error that “Posts is invalid”. This is because post.rb includes the
Thanks in advance.
The usual solution is:

class Topic
def text=(text)
# Rails should be setting the belongs-to object automatically here => text, :topic => self)
text # Make sure you return something that’s expected

class Post
validates_presence_of :topic

Rails Wheels - Find Plugins, List & Sell Plugins -

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