Domanda

I have a model called Nonsense which has_one of Foo and Bar

In my controller for Nonsense I need to create the related entries for Foo and Bar

The reason I have to create those I that I need to show the links to Foo and Bar in the new action, because of the nature of the application the details for Nonsense might not be known until Foo and Bar have been filled out.

What I'm trying to do in the new action for Nonsense is this

def new
  @nonsense = Nonsense.new
  @nonsense.bar = Bar.new
  @nonsense.foo = Foo.new
...

now the problem I am encountering is that in the show view that the path helper will complain about the id for @nonsense.foo and @nonsense.bar are nil.

In the show view I just do @nonsense = Nonsense.find(params[:id]) and nonsense accepts_nested_attributes_for :foo, :bar

Any idea why this would happen?

È stato utile?

Soluzione

I don't think Bar.new actually creates an object in the database, so the id is actually still nil. If you want a link to those objects, you will need to save them first.

Can you save them with some default details? I haven't used rails much, but I think you need to be careful to clean those out if you don't end up committing Nonsense. More importantly, I suspect your workflow and/or data model need to be straightened out, but maybe I am just not familiar with more complex rails setups.

Finally, If all these things are dependent and part of your Model logic, then you should probably be creating those objects in the Nonsense model and attaching everything that the controller needs. Otherwise you are letting your Model logic leak into the controller.

To be more explicit (I'm pretty sure this is bad rails form by the way, even if it works):

def new
  @nonsense = Nonsense.new

  @nonsense.bar = Bar.new
  @nonsense.bar.any_necessary_attributes = some_value
  @nonsense.bar.save

  @nonsense.foo = Foo.new
  @nonsense.foo.any_necessary_attributes = some_value
  @nonsense.foo.save
...
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top