Ruby on rails rails有很多:通过表don';我不能得救
我是rails新手,所以要小心那些丑陋的代码。 我有这些模型Ruby on rails rails有很多:通过表don';我不能得救,ruby-on-rails,associations,models,Ruby On Rails,Associations,Models,我是rails新手,所以要小心那些丑陋的代码。 我有这些模型 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_pla
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
将“打印”正确的数据,但未保存在数据库中!我使用sqlitebrowser来直观地检查它,我确信它没有被保存
顺便说一句,作为第二个问题,如果有人知道如何在没有上面难看的代码的情况下访问关联对象,我也非常感谢
第三个也是最后一个问题:
步骤=[]
played.steps.split(“;”)。如果要在
保存
失败时引发异常,请调用保存!
;否则,如果继续使用保存
,则应检查返回的布尔值以查看保存是否成功
false
返回值将指示验证失败。失败的详细信息将在模型的错误信息中
关于以更好的方式获得关联:可能您可以使用作用域来做一些事情,甚至只需编写一个方法来封装您正在尝试做的事情
关于解码这些步骤,你可以使用
inject
而不是每一个,但这仍然是一个逻辑性很强的问题。我建议用一个描述性名称来封装它,比如decode\u steps
或类似的方法。尝试更改played.steps我不知道为什么,但改为played.steps=played.steps+“#{from}:#{to};”使它工作了!我的想法是ActiveRecord没有注意到在使用
#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
# pl = current_user.games_playeds.find_by_game_id (game.id)
# raise pl.steps