dschatz
dschatz

Reputation: 1218

Accessing id in a just built object

I have a rails app where I have clusters and users in a belongs_to has_many relationship.

In the cluster_controller create method I write:

@cluster = @current_user.clusters.build(params[:cluster])

now I want to run some commandline script:

output = `echo cluster#{@cluster.id} > /tmp/out`

...rest of function here

I also tried

output = `echo cluster#{@cluster.id.to_s} > /tmp/out`

When I do this the file has just cluster in it and not cluster#. Why is this and how do I fix it?

Upvotes: 0

Views: 71

Answers (1)

Greg Campbell
Greg Campbell

Reputation: 15302

The build method initializes a new ActiveRecord object, but does not persist it to the database; generally, the id attribute is only set once the record has been saved (assuming it's a standard autoincrement primary key). You probably want to use create rather than build.

Upvotes: 6

Related Questions