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.
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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With