Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way around putting hidden field in forms for resources with belongs_to association

I'm learning Rails by writing simple TODO tasks aplication. Two models are:

class List < ActiveRecord::Base
  has_many :tasks, :dependent => :destroy
  # ...
end

class Task < ActiveRecord::Base
  belongs_to :list
  # ...
end

Tasks are routed as a nested resources under Lists. So when a new Task is created by user a POST message is sent to /lists/:list_id/tasks. So far in Tasks#new view's form there is

f.hidden_field :list_id, :value => params[:list_id]

but it's a terrible solution, because anyone can change value of that hidden field.

What is the convention here? Should I put something like

@task.list_id = params[:list_id]

in Tasks#create action and get rid of the hidden field, or maybe

@task = List.find(params[:list_id]).tasks.new(params[:task])
if @task.save
  # ...
end

or there is even a better way I don't know about?

Edit:
Yeah, well there was similar question and its answer is pretty much covering my question. If you have different one please post it.

like image 220
Tomasz Cudziło Avatar asked Jul 26 '10 23:07

Tomasz Cudziło


1 Answers

You're right - that would be horrible. No need for hidden fields. Something like the following.

In your TasksController:

def new
  @list = List.find(params[:list_id])
  @task = @list.tasks.build
end

def create
  @list = List.find(params[:list_id])
  @task = @list.tasks.new(params[:task])

  # etc
end

In your Task#new view:

<% form_for [@list, @task] ... %>
  ...
<% end %>
like image 165
bjg Avatar answered Sep 20 '22 21:09

bjg