我有一个关于rails及其关系查询构建器的问题,特别是如何将camel案例转换为相关的调用。
相关守则
class CustomerPlan < ActiveRecord::Base
attr_accessible :customer_id, :plan_id, :startDate, :user_id
has_many :planActions
end
class PlanAction < ActiveRecord::Base
attr_accessible :actionType_id, :customerPlan_id, :notes, :timeSpent
belongs_to :customerPlan
belongs_to :actionType
endgetters和setter工作得很好,例如plan_action.actionType.name将正确地从相关模型中提取。但是,customer_plan.planActions.each返回错误:
SQLite3::SQLException: no such column: plan_actions.customer_plan_id:
SELECT "plan_actions".*
FROM "plan_actions"
WHERE "plan_actions"."customer_plan_id" = 1该列在数据库中被定义为customerPlan_id,难道我使用它是错误的吗?它适用于每一个其他电话,我所有的其他关系都很好。甚至PlanAction -> CustomerPlan。
我浏览了所有的医生们,并搜索了我所知道的所有其他来源。它很简单,足以改变我的专栏,我只是想知道这里发生了什么。
谢谢您抽时间见我!
解决这个问题的一个快速方法就是显式地设置foreign_key。
has_many :planActions, :foreign_key => "customerPlan_id", :class_name => "PlanAction"尽管如此,我还是觉得我错过了一些模特儿命名的约定,只是似乎想不出是什么。
发布于 2012-10-13 00:49:03
Rails对DB列名的约定是使用小写字母,用下划线分隔单词(例如,author_id、comments_count、updated_at等)。
我强烈建议您坚持Rails约定。这样你的生活就容易多了。要将其更改为rails约定,只需创建一个迁移,将该列重命名为适当的样式。
但是,如果您确实希望对列名使用自定义样式,rails将在:foreign_key关系中提供许多选项来指定预期的外部列名:
class CustomerPlan < ActiveRecord::Base
has_many :plan_actions, :foreign_key => 'customerPlan_id'
end如果希望使用与实际DB列名不同的模型属性名称,也可以使用alias_attribute宏来别名列名。但是,正如我所提到的,我建议尽可能坚持rails公约。过会儿你会感谢我的。
发布于 2012-10-13 03:20:15
Rails有3种基本的命名方案。
一个是常量,它是ALL_UPPERCASE_SEPARATED_BY_UNDERSCORES。
一个是用于类,它是AllCamelCaseWithNoUnderscores。
一种是用于变量和方法名,即all_lowercase_separated_by_underscores。
之所以会出现这种情况,不仅仅是为了一致性,还因为它可以使用这些方法在它们之间自由地进行转换。
因此,要使您的发布代码更加rails-y:
class CustomerPlan < ActiveRecord::Base
attr_accessible :customer_id, :plan_id, :start_date, :user_id
has_many :plan_actions
end
class PlanAction < ActiveRecord::Base
attr_accessible :action_type_id, :customer_plan_id, :notes, :time_spent
belongs_to :customer_plan
belongs_to :action_type
endhttps://stackoverflow.com/questions/12868622
复制相似问题