开发者

Rails build function with 2 Objects

I have a problem concerning the build method in rails 3. I want to create a Todo with foreignkeys of project and group.

The associations look like

Group has_many projects and todos

Project has_many todos, belongs_to group

Todo belongs_to 1 project and 1 group

My routes
resources :groups do
        resources :projects do
            resources :todos
        end
end

work perfect.

The form also works 开发者_开发知识库perfectly with:

<%= form_for [@group, @project, @todo] do |f| %>

My problem is now the CREATE and UPDATE Method in the Todo-Controller.

   def create
        @group   = Group.find(params[:group_id])
        @project = Project.find(params[:project_id])
        @todo = @group.projects.todos.build(params[:todo])
        @todo.save
   ... 

If I write:

@todo = @group.todos.build(params[:todo]) 

or @todo = @project.todos.build(params[:todo])

the project_id OR group_id is saved in the database. But not with:

@todo = @group.projects.todos.build(params[:todo])

My question is now, how I can get access of the group_id and the project_id and save them both into the database.


Finally I found a working solution:

    @group  = Group.find(params[:group_id])
    @todo   = @group.todos.build(params[:todo])    
    @todo.project = Project.find(params[:project_id])
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜