这是之前this个问题的答案.事实上,我发现我可以从该查询中删除连接,所以现在工作查询是

start_cards = DeckCard.find :all, :joins => [:card], :conditions => ["deck_cards.deck_id = ? and cards.start_card = ?", @game.deck.id, true]  

这似乎奏效了.然而,当我try 将这些DeckCard移动到另一个关联中时,我会遇到ActiveRecord::ReadOnlyRecord错误.

这是密码

for player in @game.players 
  player.tableau = Tableau.new
  start_card = start_cards.pop 
  start_card.draw_pile = false
  player.tableau.deck_cards << start_card  # the error occurs on this line
end

以及相关模型(tableau是桌上的玩家卡)

class Player < ActiveRecord::Base
  belongs_to :game
  belongs_to :user
  has_one :hand
  has_one :tableau
end

class Tableau < ActiveRecord::Base
  belongs_to :player
  has_many :deck_cards
end  

class DeckCard < ActiveRecord::Base
  belongs_to :card
  belongs_to :deck  
end

我在这段代码之后做了一个类似的操作,在玩家的手上加了DeckCards,代码运行良好.我想知道我是否需要在DeckCard模型中使用belongs_to :tableau,但它可以很好地添加到玩家的手上.DeckCard表中有tableau_idhand_id列.

我在rails api中查找了ReadOnlyRecord,它没有超出描述的内容.

推荐答案

Rails 2.3.3 and lower

ActiveRecord CHANGELOG(v1.12.012005年10月16日):

Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around.

使用find_by_sql实际上不是一种替代方法,因为它返回的是原始的行/列数据,而不是ActiveRecords.你有两个 Select :

  1. 强制实例变量@readonly在记录中为false(hack)
  2. 使用:include => :card而不是:join => :card

Rails 2.3.4 and above

在2012年9月10日之后,上述大部分不再成立:

  • 使用Record.find_by_sql is是一个可行的 Select
  • 如果:joins被指定为without显式:select nor显式(或查找器范围继承):readonly选项(请参见Rails 2.3.4的set_readonly_option! in active_record/base.rb实现,或Rails 3.0.0的to_a in active_record/relation.rbcustom_join_sql in active_record/relation/query_methods.rb实现),则:readonly => true将自动推断为only
  • 但是,如果联接表包含两个以上的外键列,并且指定:joins时没有明确的:select,则在has_and_belongs_to_many中总是自动推断出:readonly => true(即忽略用户提供的:readonly个值——参见active_record/associations/has_and_belongs_to_many_association.rb中的finding_with_ambiguous_select?)
  • 总之,除非处理特殊的联接表和has_and_belongs_to_many,否则@aaronrustad的答案在Rails 2.3.4和3.0.0中适用.
  • 如果你想达到INNER JOIN(:includes意味着LEFT OUTER JOIN,它的 Select 性和效率都不如INNER JOIN)

Ruby-on-rails相关问答推荐

在has_many关系中由两个条件 Select

在VP中部署rails 7和nginx

无法安装Ruby错误运行';__rvm_make-J4';,

如何在嵌套路由中使用Ruby on rails多态关联

RubyOnRail在测试环境中启动失败

是否从已转换为字符串的数组中提取符号?

合成轨道布局

为什么在使用 Ruby on Rails 时我的徽标没有出现在 Bootstrap 导航栏中?

如何断言 Ruby 单元测试中的错误消息?

Rails 7.0.4 和 link_to 的数据确认不起作用

Devise + Omniauth - 如何传递额外的参数?

rails 3.2 迁移无法在更改方法中向 create_table 添加索引

rails 模型 has_many 本身

Ruby on Rails:调试 rake 任务

在 Rails 中复制模型实例

在 Rails 协会中未找到名为的协会可能拼写错误的问题

通过get in rails传递参数数组

Coffeescript ||= 模拟?

在 Rails 3 中设置会话超时

如何删除特殊字符?