我有一個通過設計創建的用戶模型,一個股票模型(通過腳手架生成),因此我可以用我自己的定製價格創建股票數據庫,以及一個UserStock模型來建立關聯兩者之間。在我的用戶界面和我的控制檯中,似乎一切正常。在導軌中刪除和重新創建相同的關聯
這裏是捕獲。 我有一個刪除方法綁定到在我的_list.html.erb中配置的按鈕,該按鈕顯示用戶投資組合中的所有股票。當我第一次刪除它(從我的投資組合中刪除股票),它工作正常。當我再次將股票添加到我的投資組合時,當然工作良好。但第二次刪除不起作用。 例如說,我的用戶ID是1.我的UserStock關聯在user_id 1和stock_id 1之間創建關聯(比如說,ID爲1的股票是Google)。這存儲在UserStock ID 1中。當我刪除此關聯並重新創建時,它將存儲在UserStock ID 2(一個全新的關聯)中。但是當我嘗試再次刪除它時,我無法這樣做。我的導軌控制檯在我的UserStock控制器中指出了這個錯誤。
這是彈出的錯誤:記錄在UserStocksController未找到#破壞
def set_user_stock
@user_stock= UserStock.find(params[:id])
end
編輯:好的,這是我的觀點和需要的車型:
<% if @user.id = current_user.id %>
<td>
<%=link_to "Delete", user_stock_path(user_stock), :method
=> :delete, :data => { :confirm => "Are you sure?" },
:class => "btn btn-xs btn-danger" %>
</td>
<% end %>
user.rb
has_many :user_stocks
has_many :stocks, through: :user_stocks
def can_add_stock?(ticker_symbol)
!stock_already_added?(ticker_symbol)
end
def stock_already_added?(ticker_symbol)
stock = Stock.find_by_ticker(ticker_symbol)
return false unless stock
user_stocks.where(stock_id: stock.id).exists?
end
stock.rb
has_many :user_stocks
has_many :users, through: :user_stocks
def self.find_by_ticker(ticker_symbol)
where(ticker: ticker_symbol).first
end
user_stock.rb
belongs_to :user
belongs_to :stock
你認爲哪種視圖以及該視圖的代碼是什麼樣的?我會說,這是不尋常的,你會有一個連接表的控制器。通常你會使用像Users控制器這樣的東西,並用'@ user.user_stocks'找到UserStock,並且你可以附加你的刪除。 –
您需要向我們展示您的視圖以及相關模型,以便我們爲您提供幫助。 – the12
@ruby_newbie我知道這很不尋常。這只是爲了方便客戶(因爲這是一個股票交易遊戲,他們更容易看到參與者通過此表追蹤的股票)。但它應該仍然有效。我已經更新了我的代碼。 – Solias