[英]Accessing model attributes in ActiveSupport::Concern module
I have some models which share the same functionality just on other paths. 我有一些在其他路径上共享相同功能的模型。 So I decided to put these methods in a module and set the path in the model.
因此,我决定将这些方法放在模块中并在模型中设置路径。 My problem is that I'm not able to access the attribute in my module.
我的问题是我无法访问模块中的属性。
model: 模型:
class Job < ActiveRecord::Base
include ImageModel
image_dir = "jobs"
end
module: 模块:
module ImageModel
extend ActiveSupport::Concern
def delete_image
unless pic_link == "" || pic_link == nil
begin
if File.delete(Rails.root.join("public", "images", image_dir, pic_link))
return true
else
return false
end
rescue
return true #an error occured but when the image does not exist we still return true
end
end
return true
end
def replace_image(new_image)
File.open(Rails.root.join("public", "images", image_dir, new_image.original_filename), "wb") do |f|
if f.write new_image.read
delete_image
pic_link = new_image.original_filename
return true #everything went fine
else
return false #return false if new image could not be written
end
end
end
end
The error i get: 我得到的错误:
undefined local variable or method `image_dir' for #<Job:0x007f8a93b9e8d8>
on this line: 在这条线上:
File.open(Rails.root.join("public", "images", image_dir, new_image.original_filename), "wb") do |f|
Did I miss something or did I oversee something important? 我错过了一些事情还是监督了一些重要的事情?
Felix 费利克斯
I think the design of module still have room to improve. 我认为模块的设计仍有改进的空间。 But for this specific question, here is the quickfix.
但是对于这个特定的问题,这里是快速修复。
class Job < ActiveRecord::Base
include ImageModel
def image_dir
"jobs"
end
end
You should define your image_dir = "jobs"
in the module itself. 您应该在模块本身中定义
image_dir = "jobs"
。 because you are including your module in your model, and your module is not able to get the declaration, you have done in your model. 因为您要在模型中包含模块,并且模块无法获取声明,所以您已经在模型中完成了。
Or you can change your delete_image
method to take parameters : 或者,您可以将
delete_image
方法更改为采用参数:
def delete_image(image_dir)
unless pic_link == "" || pic_link == nil
begin
if File.delete(Rails.root.join("public", "images", image_dir, pic_link))
return true
else
return false
end
rescue
return true #an error occured but when the image does not exist we still return true
end
end
return true
end
and where you are calling that method, pass an argument like this: 并在调用该方法的地方传递如下参数:
delete_image("jobs")
same in the case of replace_image
method: 对于
replace_image
方法相同:
def replace_image(new_image, image_dir)
File.open(Rails.root.join("public", "images", image_dir, new_image.original_filename), "wb") do |f|
if f.write new_image.read
delete_image
pic_link = new_image.original_filename
return true #everything went fine
else
return false #return false if new image could not be written
end
end
end
Hope it will help. 希望它会有所帮助。 Thanks
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.