如果未设置关联,则创建模型方法
Create a model method if association is not set
我有一个 Post
模型 belongs_to :author
。如果作者在创建时设置在 post 上,post.author
return 就是作者。但是,如果未在 post 上设置作者,我希望在调用 post.author
时仍然 return 默认作者。我有以下内容:
class Post
belongs_to :author
def author
begin
Author.find(read_attribute("author_id"))
rescue
Author.default_author
end
end
end
我的问题是覆盖关联方法是否可以author
。这会导致协会等的任何内部处理被绕过吗?有一个更好的方法吗?例如,我应该改用 method_missing
之类的东西吗?
如果它是空白的,我会设置它before_validation
class Post < ActiveRecord::Base
belongs_to :author
before_validation :set_author
validates :author, :presence => true
def set_author
self.author = Author.default if author.blank?
end
end
在你的具体情况下,我不推荐
overriding the association method author
与数据库中的列同名,因为如果你想到另一个开发者在你后面,他们不会很明显地调用 post 上的作者属性不只是 return 作者列的数据,但实际上 return 是默认作者,如果它不存在的话。
因此,出于这个原因,我会说您需要创建一个名为 author_or_default_author
之类的新方法,因此希望很明显该方法是什么 returns
此外,在您的模型中覆盖该列名称实际上会 运行 当您只是简单地尝试创建作者记录时编写该代码。这是否可取,对于其他开发人员来说绝对不会显而易见
你可以考虑做这样的事情
class Post
belongs_to :author
def author_or_default_author
Author.where(id: author_id).present? || Author.default_author
end
end
并用
调用它
post.author_or_default_author
在我上面的示例中使用 .where 的一个好处是您不必处理 activerecord not found
类型的错误,如果您尝试 Author.find(1234) 而 1234 不是' 一个有效的作者 ID。所以你可以摆脱你使用的begin and rescue
#app/models/post.rb
class Post < ActiveRecord::Base
before_create :set_author, unless: Proc.new {|post| post.author.present? }
private
def set_author
self.author_id = "2"
end
end
我有一个 Post
模型 belongs_to :author
。如果作者在创建时设置在 post 上,post.author
return 就是作者。但是,如果未在 post 上设置作者,我希望在调用 post.author
时仍然 return 默认作者。我有以下内容:
class Post
belongs_to :author
def author
begin
Author.find(read_attribute("author_id"))
rescue
Author.default_author
end
end
end
我的问题是覆盖关联方法是否可以author
。这会导致协会等的任何内部处理被绕过吗?有一个更好的方法吗?例如,我应该改用 method_missing
之类的东西吗?
如果它是空白的,我会设置它before_validation
class Post < ActiveRecord::Base
belongs_to :author
before_validation :set_author
validates :author, :presence => true
def set_author
self.author = Author.default if author.blank?
end
end
在你的具体情况下,我不推荐
overriding the association method author
与数据库中的列同名,因为如果你想到另一个开发者在你后面,他们不会很明显地调用 post 上的作者属性不只是 return 作者列的数据,但实际上 return 是默认作者,如果它不存在的话。
因此,出于这个原因,我会说您需要创建一个名为 author_or_default_author
之类的新方法,因此希望很明显该方法是什么 returns
此外,在您的模型中覆盖该列名称实际上会 运行 当您只是简单地尝试创建作者记录时编写该代码。这是否可取,对于其他开发人员来说绝对不会显而易见
你可以考虑做这样的事情
class Post
belongs_to :author
def author_or_default_author
Author.where(id: author_id).present? || Author.default_author
end
end
并用
调用它post.author_or_default_author
在我上面的示例中使用 .where 的一个好处是您不必处理 activerecord not found
类型的错误,如果您尝试 Author.find(1234) 而 1234 不是' 一个有效的作者 ID。所以你可以摆脱你使用的begin and rescue
#app/models/post.rb
class Post < ActiveRecord::Base
before_create :set_author, unless: Proc.new {|post| post.author.present? }
private
def set_author
self.author_id = "2"
end
end