开发者

Can't find xyz without ID

I am getting the erro开发者_如何转开发r "Can't find Goal with an ID" but I am not sure where I am going wrong with the code

The models are as follows:

A Goal has_many Tasks 
A Task belongs_to Goal

The create Task is as follows:

routes.rb is:

resources :goals, :only => [:create, :destroy, :show, :index]
resources :tasks, :only => [:create, :destroy, :show, :index]

goals_controller.rb#show is:

def show
     @goal = Goal.find(params[:id])
     @tasks = @goal.tasks
     @task = Task.new if signed_in?      
end

tasks_controller.rb#create is:

def create
  **@goal = Goal.find(params[:id])** 
  @task  = @goal.tasks.build(params[:task])
  if @task.save
    flash[:success] = "Task created!"
    redirect_to goal_path(@task.goal.id)
  else
    render home_path
  end
end

The line in bold is where the error is occurring. I have noticed the following:

   @goal = Goal.find(params[:goal_id]) does not work either
   @goal = Goal.find(34) works, and so do other integers I enter here

I am not sure what the issue is, as I've followed the same process which has worked for me previously but I've done something wrong this time.

I should also state the the tasks form is on the goal#show page.


I have found the solution to this. I needed a hidden field in the form to pass the id through to the create method in the tasks controller.

<%= hidden_field_tag :goal_id, @goal.id %>

Hope this can help someone else too!


You're not passing params[:id] to the create action at all. This is why you're getting this error.


I highly recommend using nested routes, for example:

resources :goals, :only => [:create, :destroy, :show, :index] do 
  resources :tasks, :only => [:create, :destroy, :show, :index]
end

Then you can use:

@goal = Goal.find(params[:goal_id])

... in your create actions.

But note that you would need to change the URL generators in your views for this, for example:

new_goal_task_path(@goal, @task)

And your form needs to be modified accordingly. You can use things like nested forms very effectively in your case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜