Rails link_to从控制器动作更新属性



我希望能够有一个链接,当按下更新一个基于控制器动作的属性。我怎么能这么做呢?我必须创建一个单独的更新路由吗?我是新手,所以请原谅我。

控制器

def completed
 @meeting = Meeting.find(params[:id])
 if @meeting.day_of_meeting == @meeting.days
  @meeting.update_attribute(:day_of_meeting, '1')
  redirect_to :back
 else
  @meeting.increment!
  redirect_to :back
 end
end

模型
def increment!
  update_attribute(:day_of_meeting, day_of_meeting + 1)
end
视图

<%= link_to meetings_completed_path(@meeting), remote: true do %>

路线

resources :meetings do
  get 'meetings/completed'
end

你的代码有几个问题

  1. 由于您正在更新记录,您需要在链接中包含method: :patch,并且您还需要修改路由文件以包含适当的路由。

    在路由文件中添加

    #routes.rb
    resources :meetings do
      member do
        patch 'completed'
      end
    end
    

    在你的视图

    <%= link_to "Mark as completed", completed_meeting_path(@meeting), remote: true, method: :patch  %>
    
  2. 因为你有一个remote:true在你的链接,所以rails会尝试渲染一个javascript模板,因为你没有渲染一个javascript模板,你会得到一个模板缺失的错误

    在控制器

    def completed
      @meeting = Meeting.find(params[:id])
      respond_to do |format|
        # if something ...
          # update meeting record and then render js template
          format.js {render :status => :ok} # it will render completed.js.erb inside 'app/views/meetings/' directory
        # else
          # something else
          format.js {render :action => "different_action"} # it will render different_action.js.erb inside 'app/views/meetings/' directory 
      end
    end 
    

现在你需要做的就是在js模板中编写一些基本的javascript来更新视图。

注意:如果你不想渲染任何简单使用format.js { render :nothing => true }。此外,如果你想使用redirect_to调用而不是渲染js模板,只需删除remote: true形式你的链接。

您可以在set_member_album =: image_capa

中设置动作
#app/controllers/member/albums_controller.rb
class Member::AlbumsController < ApplicationController
before_action :set_member_album, only: [:show, :edit, :update, :destroy, :image_capa]
  #PATCH/PUT /adm/image_capa/1
  def image_capa
    # @member_album = Member::Album.find(params[:id]) # sempre colocar a action before_action :set_member_album, only: [:show, :edit, :update, :destroy, :image_capa]
    if @member_album.update(image_capa: params[:image_capa])
      respond_to do |format|
        format.html { redirect_to member_albums_url, notice: t('albums.image_capa_success') }
        format.json { head :no_content }
      end
    end
  end
private
    # Use callbacks to share common setup or constraints between actions.
    def set_member_album
      @member_album = Member::Album.find(params[:id])
    end
end

相关内容

  • 没有找到相关文章

最新更新