开发者

Make a rails model interpret a value that isn't a column in the table

I use a series of named scopes on a model to generate a query.In that query there's a jo开发者_JAVA百科in with another table in which I have some boolean fields. When I access the values of those columns it returns strings("0" and "1").

Is there a DRY way to tell the model how to interpret those columns?(I know i can write methods to override the accesor, but that doesn't feel right).

I'm using rails 2.3.8.


If by "override the accessor" you meant read_attribute and write_attribute methods, then this is absolutely the correct way to do this. Rails type casts fields automatically and AFAIK there is no direct way to influence type casting, only overriding setters/getters.

For integrity's sake, an example:

def admin_user
  read_attribute(:admin_user) == "1" ? true : false
end

def admin_user(v)
  write_attribute(v ? "1" : "0")
end

Note: for more complex cases (say password encryption) the best way would be ActiveRecord Callbacks. Take a look at the examples there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜