开发者

Customizing multiple submit tags in rails 3 form_for

I set up a form_for 开发者_高级运维to review submitted images in my site but I was hoping there was way to have multiple submit tags that not only commit the changes but also send in a value to a field?

So that way if I click a "approve image" button then the form is submitted and my "status" field is set with "approved"

I have no idea how to do this haha.


You have access to the button which was pressed in the params hash. Assuming you have REST-ful controllers, this is my fast and dirty solution:

# images_controller.rb
def update
  @image = Image.find(params[:id])
  case params[:commit] # Value of button (which is shown as the text of the button in browsers)
  when 'approve image'
    @image.status = 'approved'
  when 'other status'
    ...
  else
    @image.status = 'flagged'
  end
  @image.save
  # Redirect or whatever
end

Better solution:

# images_controller
before_filter :set_status

def update
  @image = Image.find(params[:id])
  @image.update_attributes(params[:image|)
  # Redirect
end

private
def set_status
  params[:image][:status] = case params[:commit]
  when 'approve image'
    'approved'
  ...
  else
    'flagged'
  end
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜