Ruby on rails 在模型中有条件地设置数据库值
基本上:Ruby on rails 在模型中有条件地设置数据库值,ruby-on-rails,activerecord,model,Ruby On Rails,Activerecord,Model,基本上: 我想将修订版的标题设置为它是修订版的帖子的标题 如果新帖子不是修订版(或是\u revision=false),我想将revision\u id设置为id) 到目前为止,我在这方面遇到了很多麻烦。谢谢你的帮助 post.rb class Post < ActiveRecord::Base has_many :revisions, class_name: "Post", foreign_key: "revision_id" belongs_to :revision, clas
- 我想将修订版的
标题设置为它是修订版的帖子的标题李>
- 如果新帖子不是修订版(或
),我想将是\u revision=false
设置为revision\u id
)id
- 如果新帖子不是修订版(或
class Post < ActiveRecord::Base
has_many :revisions, class_name: "Post", foreign_key: "revision_id"
belongs_to :revision, class_name: "Post"
#...
before_save :post_title
def post_title
if :is_revision == false
@revision_id = @post_id
elsif :is_revision == true
:revision_id != :post_id
@title = @revision.title
end
end
#...
end
我不太明白你的逻辑,也许你应该告诉我们一些背景 否则,您是否只是尝试:
class Post < ActiveRecord::Base
has_many :revisions, class_name: "Post", foreign_key: "revision_id"
belongs_to :revision, class_name: "Post"
#...
before_save :set_title_to_revision_title, :if => :is_revision?
# Need to be called after the save because post.id will not be available on the create
after_save :update_revision_id_to_id, :unless => :is_revision?
def is_revision?
@is_revision
end
def set_title_to_revision_title
@title = @revision.title
end
def update_revision_id_to_id
# just make a quick call to update it i
update_attribute :revision_id, @id
end
#...
end
class Post:是否修订?
#需要在保存后调用,因为在创建时post.id将不可用
保存后:将修订版\u id\u更新为\u id,:除非=>:是否修订?
def是修订版吗?
@是修订版吗
终止
def将标题设置为修订标题
@title=@revision.title
终止
def更新_版本_id_至_id
#只要打个电话更新一下我就知道了
更新属性:修订号,@id
终止
#...
终止
if:is\u revision==false的语法是错误的。您正在将符号与布尔值进行比较。尝试在控制台中使用模型实例运行代码,以确保调用的方法正确。在这种情况下,我会调用@revision\u id
还是self.revision\u id
?@aceofspades:我现在可以通过控制器使其工作,但是,在模型中使用它是理想的。任何建议。我会相应地更新帖子。我会尝试一下并让你知道。用户可以选择他们的帖子是新帖子还是其他帖子的修订版(通过is\u revision
Boolean)。当它是一篇文章时,我想用id填充外键id(revision\u id
)。当它是一篇修订版时,我想使用它是一篇修订版的文章的标题。这些帖子都是上传中的作品,修改很难实现。我不确定这种递归性是实现你想要的最好的方法。我的意思是,如果这是一篇文章,根据定义它不是一篇修订,所以你不应该填写revision\u id
。你可以修改方法is\u revision?
,使其返回@revision\u id.nil?
,甚至可以创建一个范围:revisions
,以查询所有属于修订的帖子。此外,我认为您错误地命名了列revision\u id
,实际上revision\u id
指的是一个修订,但在这种情况下,您指的是父帖子,如果我是您,我会将其命名为parent\u id
或post\u id
。
class Post < ActiveRecord::Base
has_many :revisions, class_name: "Post", foreign_key: "revision_id"
belongs_to :revision, class_name: "Post"
#...
before_save :set_title_to_revision_title, :if => :is_revision?
# Need to be called after the save because post.id will not be available on the create
after_save :update_revision_id_to_id, :unless => :is_revision?
def is_revision?
@is_revision
end
def set_title_to_revision_title
@title = @revision.title
end
def update_revision_id_to_id
# just make a quick call to update it i
update_attribute :revision_id, @id
end
#...
end