繁体   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