簡體   English   中英

rails link_to帖子到錯誤的id - 為什么?

[英]rails link_to posts to incorrect id - why?

我希望我的用戶能夠更改他們擁有的Share上的布爾值,但我的實現嘗試更新了錯誤的記錄。

當我去表演頁的Itemid:7 ,我控制器加載相關Share通過尋找對象Share的是含有S item_id設置為7.當我然后點擊HideShow按鈕,我的代碼更新相關Shareactive屬性,然后重定向到同一個Item

但是,如果我轉到顯示頁面找到id:3Item ,然后單擊相同的按鈕,我的代碼會重定向到並使用item_id:7更新Shareactive屬性,而不是item_id:3 任何人都可以告訴我為什么會這樣嗎?

我的分享模式:

class Share < ActiveRecord::Base
 belongs_to :user
 belongs_to :item

 def activate
  self.active = true
  save
 end

 def deactivate
  self.active = false
  save
 end
end

我的物品型號:

 class Item < ActiveRecord::Base
  has_many :shares
 end

在我的ItemsController#show action中,我有這個:

def show
 @item = Item.friendly.find(params[:id])
 @owned_share = current_user.shares.find_by(item_id: @item.id)
end

在我的SharesController ,我有這個:

def activate
 @owned_share = current_user.shares.find_by(params[:item_id])
 @owned_share.activate
 respond_to do |format|
  format.html { redirect_to item_path(@owned_share.item) }
  format.json { render :index, status: :ok, location: @owned_share }
 end
end

def deactivate
 @owned_share = current_user.shares.find_by(params[:item_id])
 @owned_share.deactivate
 respond_to do |format|
  format.html { redirect_to item_path(@owned_share.item) }
  format.json { render :index, status: :ok, location: @owned_share }
 end
end

在我的項目展示視圖中,我有這個:

<% if @owned_share.active == true %>
 <div class="eight wide column">
  <%= link_to "Hide", share_deactivate_path(@owned_share.item), class: "button wide-button functional-red-button", method: :post %>
 </div>
<% else %>
 <div class="eight wide column">
  <%= link_to "Show", share_activate_path(@owned_share.item), class: "button wide-button functional-mint-button", method: :post %>
 </div>
<% end %>

正如評論中所述,您收到的參數不是item_id ,而是share_id ,這就是為什么盡管您修改了查詢添加要查找的屬性,但它並沒有為您提供預期的結果。

更新用於獲取用戶共享的參數,例如:

@owned_share = current_user.shares.find_by(item_id: params[:share_id])

雖然在這種情況下不清楚為什么你使用share_id來查找item_id,但很可能你也可以更新那個部分。

由於兩個操作共享某些特定功能,因此您只需創建一個只更新活動屬性“翻轉”其值的文件:

# model
def toggle_active
  update(active: !active)
end

# controller
def update_active_status
  @owned_share = current_user.shares.find_by(item_id: params[:share_id])
  @owned_share.toggle_active
  respond_to do |format|
    format.html { redirect_to item_path(@owned_share.item) }
    format.json { render :index, status: :ok, location: @owned_share }
  end
end

它獲取當前用戶的共享活動值並使用它來替換它! 請注意,如果它們沒有默認值,則nil的否定返回true。

!true  # false
!false # true
!nil   # true

注意@owned_share.active == true也可以是@owned_share.active? @owned_share.active

因為這:

@owned_share = current_user.shares.find_by(params[:item_id])

應該:

@owned_share = current_user.shares.find_by_item_id(params[:item_id])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM