开发者

What is the shortest way in ruby to write these four instructions?

开发者 https://www.devze.com 2023-04-13 10:05 出处:网络
u = User.email_equals("tabaluga@gmail.com").first s = u.setting s.regular_info = false s.save Does anyone know how 开发者_JAVA技巧to write it shorter? Perhaps in one line? That would be awe
u = User.email_equals("tabaluga@gmail.com").first
s = u.setting
s.regular_info = false
s.save

Does anyone know how 开发者_JAVA技巧to write it shorter? Perhaps in one line? That would be awesome.


User.email_equals("tabaluga@gmail.com").first.setting.update_attribute(:regular_info, false)

(don't have a console handy to check, but think that should work ..)


I'm not sure how do you define your email_equals method, but Rails provides Dynamic attribute-based finders which returns the first match or nil for not found.

User.find_by_email("tabaluga@gmail.com").setting.update_attribute(:regular_info, false)


Although you can write this in one line, I would recommend against it. This makes your code less readable and maintainable.

This is also an isolated example; realistically the email would not be hardcoded, it would be stored in its own variable and might be an argument.

One Liner

User.email_equals("tabaluga@gmail.com").first.setting.update_attribute(:regular_info, false)

Two Liner

user = User.email_equals("tabaluga@gmail.com").first
user.setting.update_attribute(:regular_info, false)

# Or...
user_setting = User.email_equals("tabaluga@gmail.com").first.setting
user_setting.update_attribute(:regular_info, false)

# More readable, but not maintainable
User.email_equals("tabaluga@gmail.com").first \ 
  .setting.update_attribute(:regular_info, false)

Three Liner

user = User.email_equals("tabaluga@gmail.com").first
setting = user.setting
setting.update_attribute(:regular_info, false)
0

精彩评论

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

关注公众号