Thalatta
Thalatta

Reputation: 4578

Rails: How to hard code field in a form_for

I am working on a Rails project that has nested resources as defined below.

  resources :projects do
    resources :entries
  end

For the entries#new form, I would like to hard code the project_id from the path projects/project_id/entries/new as the project_id field of form_for in the entries' views directory. When I write:

= f.label :project_id
%br
= f.select :project_id, @project

I get the following error:

undefined method `empty?' for #<Project:0x007fa9adc06120>

Any ideas how to send the @project as that field to the form without getting f.select errors? I believe f.select takes a colleciton and so it doesn't like me just giving it a single object as its second parameter.

Thanks for your help!

Upvotes: 3

Views: 831

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

I guess you have your @entry in the new method of your controller, something like this:

def new
  @entry = Entry.new
  # etc.

You can use this instead:

def new
  @entry = @project.entries.build
  # it will set project_id to the @project.id

and in the view:

= f.hidden_field :project_id

If you don't want to initialize with the project_id directly in the view:

= f.hidden_field :project_id, value: @project.id

Upvotes: 3

Related Questions