rails has_many:通过表不保存
我是新来的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,也可以是数字或单词
如果您想在save
没有引发异常,请拨打save!
;否则,如果您继续使用save
你应该检查返回的布尔查看保存是否成功
A false
返回值表示验证失败,失败的详细信息将在呃有关该模型的信息。
关于获得该协会以更好的方式:有可能是你可以用示波器做,甚至只是通过编写一个方法来封装你正在尝试做的。
关于解码步骤,你可以使用inject
而不是each
,但它仍然是相当重的逻辑。我建议将它封装在一个描述性名称的方法中,如decode_steps
或类似的。
我试过保存!但它不会例外 – Jordi 2011-02-16 11:44:07