我有一個Like模型,它連接用戶喜歡的項目。另外標準liked
狀態,項目可以是spinned
& pinned
,所有都是布爾字段。使用列名稱變量的導軌
就像型號
_________________________________________________
| item_id | user_id | liked | spinned | pinned |
|---------|---------|---------|----------|--------|
| 1 | 1 | true | true | false |
| 2 | 1 | false | true | true |
| 3 | 2 | true | false | false |
-------------------------------------------------
一個項目都得到通過同一AJAX
調用更新的不同的狀態,在我likes controller
調用同一action
。如果還不存在,它會創建一個類似於所需的狀態爲真的狀態。
likes_controller
def index
# get the item id
action = params[:act]
mid = params[:mid]
# gets the desired like item to see if it already exists
like = Like.where(:item_id => mid, :user_id => current_user.id).first
case action
# like the item
when "like"
# if the item doesn't exist
if like.blank?
# create the like
Like.create(:user_id => current_user.id, :item_id => mid, :liked => true)
else
# else toggle the liked status
like.toggle! :liked
end
# pin the item
when "pin"
if like.blank?
# create the like
Like.create(:user_id => current_user.id, :item_id => mid, :pinned => true)
else
# else toggle the pinned status
like.toggle! :pinned
end
# spin the item
when "spin"
if like.blank?
# create the like
Like.create(:user_id => current_user.id, :item_id => mid, :spinned => true)
else
# else toggle the spinned status
like.toggle! :spinned
end
end
end
正如你看到的,在case
代碼變得非常重複,我想知道如果我可以用我的action
(「像」,「腳」,「旋轉」)變量更有效。
通過從我的另一個參數值中發送另一個參數值,我可以很容易地將action
轉換爲相應的字段名稱(「like」=>「liked」,「pin」=>「pinned」,「spin」=>「spinned」 view
。
我可以使用它只有一塊代碼而不是3個類似的代碼嗎?
即
action = "liked" # this would change depending on the desired action
# if the item doesn't exist
if like.blank?
# original
Like.create(:user_id => current_user.id, :item_id => mid, :liked => true)
# doesn't work, how would I do this appropriately?
Like.create("user_id = ?, item_id = ?, ? = true", current_user.id, mid, action)
else
# this works!, what about SQL injection? How can I prevent this?
like.toggle!("#{action}")
end
謝謝,我真的很喜歡select或new操作符,我實現了它立即!切換狀態的解決方案更容易。 –