我的编辑操作是使用create操作而不是update

时间:2011-12-26 23:04:52

标签: ruby-on-rails

我有以下关系:

store.rb -> has_many :products
product.rb -> belongs_to :store

的routes.rb

resources :stores do
  resources :products
end

builds_controller.rb

def edit  
  @build = Build.find(params[:id])
  @user = User.find(@build.user_id)
  @hero = Hero.find(@build.hero_id)

  @heros = Hero.order('name ASC')
  @items = Item.order('name ASC')

  unless current_user.id == @user.id
    respond_to do |format| 
      format.html { redirect_to root_path, notice: 'You are only allowed to edit your own builds' }
    end
  end   
end

出于某种原因,每当我尝试转到构建的编辑页面并尝试编辑它时,它会运行创建操作,而不是更新

任何人都知道这可能是什么原因?

另外,我希望编辑页面上的表单用构建的当前数据填写。我如何实现这一目标?

我的回购:https://github.com/imjp/DotA-Items

1 个答案:

答案 0 :(得分:1)

您的问题来自您的表单:

<%= semantic_form_for([current_user, current_user.builds.build]) do |f| %>

需要

<%= semantic_form_for([@user, @build]) do |f| %>

现在,在您的new操作中,您还需要准备所需的变量:

@user = User.find(params[:user_id]) #assuming you have a path like users/id/builds/new
# or @user = current_user if that's what you want
@build = @user.builds.build

ps:您应该使用cancan gem来管理授权,而不是像if @user.id == current_user.id等那样。