2013-06-04 92 views
0

您好我想更新我的数据库(PostgreSQL)中的一个值,当用户点击某个链接,虽然我有工作,我不认为它的最佳实践。如果有人能证明我如何能更好地实现这一目标将是巨大的点击更新数据库

视图

%ul.button-group.round.even-3 
      %li= link_to '<i class="general foundicon-checkmark"></i>'.html_safe, accept_availability_path(a), :method => 'put', :remote => true, :class => 'button success tiny', :id => a.id, :disable_with => '' 

控制器

def accept 
    @availability = Availability.find(params[:id]) 
    @availability.available= true 

    respond_to do |format| 
     if @availability.update_attributes(params[:availability]) 
     format.html { render :nothing => true } 
     format.js 
     else 
     format.html { render :action => "edit" } 
     format.js 
     end 
    end 
    end 

路线

resources :availabilities do 
    put 'accept', :on => :member 
    put 'decline', :on => :member 
    end 

回答

1

没有什么特别的错与你在做什么这样做。你的控制器不需要使用update_attributes,你不会传递任何属性。你可以只save它与变化.available

def accept 
    @availability = Availability.find(params[:id]) 
    @availability.available = true 

    respond_to do |format| 
    if @availability.save 
     format.html { render :nothing => true } 
     format.js 
    else 
     format.html { render :action => "edit" } 
     format.js 
    end 
    end 
end 

你可以neaten你的路线,像这样:

resources :availabilities do 
    member do 
    put :accept 
    put :decline 
    end 
end 
+0

有没有使用链接/路由更好的办法? –

+0

他们看起来非常好。你的路线可以简化一点,回答更新。你的链接很好,'link_to_remote'曾经是做这些的方法,但是在rails 3中被弃用,赞成':remote => true'。 – Matt

+0

虽然我需要使用':method =>'put''在我的链接? –