我是新來的rails,所以要注意醜陋的代碼。 我有這些模型rails has_many:通過表不保存
class User < ActiveRecord::Base
has_many :games_playeds
has_many :games, :through => :games_playeds
end
class Game < ActiveRecord::Base
has_many :games_playeds
has_many :users, :through => :games_playeds
end
class GamesPlayed < ActiveRecord::Base
validates_presence_of :user_id, :game_id
belongs_to :user
belongs_to :game
end
遊戲描述遊戲獨立於任何用戶 GamesPlayed介紹用戶如何表現在那場比賽中(死亡,目前階段,勝等)
在這個遊戲中的每個階段用戶可以在幾種選擇中進行選擇,有些會進入後期階段,有些會讓他回去。關鍵是,一旦在一個階段做出選擇,我不允許選擇其他任何東西。 要實現這一點,我有一個步驟屬性,編碼以前的選擇,如「0:1; 1:6; 6:2」等。 GamesPlayed模型中的此屬性。
用戶導航的頁面是自動生成的,所以我不知道他們的名字,但我知道他們被稱爲XX_to_YY。我在我的控制器的方法,這將讓他們都做醜如這樣的:
#get the game name, we have several games
game = Game.find_by_name (params[:game])
#get the previous and current stage
from, to = params[:page].to_s.split("_to_")
to = to.split(".html")[0]
played = current_user.games_playeds.find_by_game_id (game.id)
steps = []
played.steps.split(";").each {|a| steps << a.split(":").first}
if steps.include? from
render :inline => "You already chose for this, go back"
else
played.steps << "#{from}:#{to};"
played.save
# pl = current_user.games_playeds.find_by_game_id (game.id)
# raise pl.steps
render "games/choosePath/#{game.name}/#{params[:page]}.html"
end
我想這是一個可怕的代碼。我對Ruby也是新手:P
現在,問題: playing.save不會給我帶來任何錯誤。
# pl = current_user.games_playeds.find_by_game_id (game.id)
# raise pl.steps
將「打印」正確的數據,但它不會保存在數據庫中!我使用sqlitebrowser來視覺檢查它,我相信它不會被保存。
順便說一句,作爲第二個問題,如果有人知道如何在沒有那麼醜陋的代碼的情況下進入關聯對象,那麼非常感謝。
以及第三和最後一個問題:
步驟= [] played.steps.split( 「;」),每個{| A |。步驟< < a.split(「:」)。首先}
這也是可怕的,但不知道如何使它變得更好(想要從aa:cc; bb:dd得到aa和bb; 「我不知道什麼是AA和BB,也可以是數字或單詞
我試過保存!但它不會例外 – Jordi 2011-02-16 11:44:07