views:

40

answers:

1

Hi,

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?

+6  A: 

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.

Greg Campbell
Thanks, heres the issue:The script might fail in which case I don't want to create the cluster. Should I just remove it from the database or is there a better way?
dschatz
You could do the create in a transaction, then roll the transaction back if the script fails. Another option would be to output some other identifying characteristic rather than id to the log - it really depends on your use case.
Greg Campbell
I just need to submit a unique value for each time I run the script which is run each time I create a cluster. I chose the id because it must be unique. Then if the script fails for whatever reason I should just redirect the user to the home page (or wherever) and let them know their cluster create failed. This of course should make no changes to the database.
dschatz
Maybe a UUID would be a good way to go - you could use http://uuidtools.rubyforge.org/ or a similar library to generate them.
Greg Campbell