[英]Rails access model attribute before save
I have notices
and comments
on those notices. 我有notices
和对这些通知的comments
。 The comments are also of class notice. 评论也是上课通知。 When a notice is submitted for creation, its commentee_id
will be blank if it is an original notice. 提交创建通知时,如果它是原始通知,则其commentee_id
将为空白。 If the notice is a comment on another notice, its commentee_id
will be the id of the notice it is commenting on. 如果该通知是对另一条通知的commentee_id
,则其commentee_id
将是对其进行commentee_id
的通知的ID。
notices_controller.rb: notices_controller.rb:
def create
@character = Character.find_by(callsign: params[:callsign])
@notice = @character.notices.build(notice_params)
if @notice.save
.
.
end
end
def notice_params
params.require(:notice).permit( :content, :picture, :latitude, :longitude,
active_comment_relationship_attributes: [:commentee_id] )
end
notice.rb: notice.rb:
belongs_to :character
has_one :active_comment_relationship, class_name: "Commentrelationship",
foreign_key: "commenter_id",
dependent: :destroy
has_one :supernotice, through: :active_comment_relationship, source: :commentee
accepts_nested_attributes_for :active_comment_relationship
before_validation :create_commentee
private
def create_commentee
if !commentee_id.blank?
create_active_comment_relationship(commentee_id: :commentee_id)
end
end
The new notice model doesn't get successfully created. 无法成功创建新的通知模型。 I get the error message: 我收到错误消息:
undefined local variable or method `commentee_id' for #<Notice:0x0000010c3a4708>)
When create_commentee
is called, the new @notice
instance has been created in memory but not yet saved to the database ( create_commentee
is a before_validation
callback). 调用create_commentee
,新的@notice
实例已在内存中创建,但尚未保存到数据库中( create_commentee
是before_validation
回调)。 At this stage, how do you correctly access commentee_id
? 在此阶段,您如何正确访问commentee_id
?
Neither this ( !commentee_id.blank?
): 都不是( !commentee_id.blank?
):
def create_commentee
if !commentee_id.blank?
create_active_comment_relationship(commentee_id: :commentee_id)
end
end
nor this ( commentee_id
not :commentee_id
): 也不是这样( commentee_id
不是:commentee_id
):
def create_commentee
if !commentee_id.blank?
create_active_comment_relationship(commentee_id: commentee_id)
end
end
makes any difference. 有所不同。
At least one problem is that you're doing this: 至少一个问题是您正在执行此操作:
if !:commentee_id.blank?
...when you should be doing this: ...当您应该这样做时:
if !commentee_id.blank?
:commentee_id
is a symbol, which is like a special kind of string, and it will never be blank (well, unless it's :""
). :commentee_id
是一个符号,就像一种特殊的字符串,并且永远不会为空(好吧,除非它是:""
)。 You want to call the commentee_id
method, ie without :
). 您要调用commentee_id
方法,即不使用:
。
PS If you want to be slightly more idiomatic, I'd recommend this instead: PS:如果您想变得更惯用,我建议改为:
if commentee_id.present?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.