Ruby on rails 控制器中的访问模型方法
我的MVC逻辑可能是错误的,但我试图做的是从视图中获取用户输入,并将该信息传递给数据库。但是在这样做之前,我想通过分析一些正则表达式(然后将类型以及内容传递给数据库)来确定提交的数据类型 但是由于某种原因,我得到了一个错误(未定义的方法'get_type'),我从模型中调用的方法不存在。我认为这种方法应该在模型中是错误的吗 控制器:Ruby on rails 控制器中的访问模型方法,ruby-on-rails,Ruby On Rails,我的MVC逻辑可能是错误的,但我试图做的是从视图中获取用户输入,并将该信息传递给数据库。但是在这样做之前,我想通过分析一些正则表达式(然后将类型以及内容传递给数据库)来确定提交的数据类型 但是由于某种原因,我得到了一个错误(未定义的方法'get_type'),我从模型中调用的方法不存在。我认为这种方法应该在模型中是错误的吗 控制器: def create @post = Post.new( content: params[:post][:content] ty
def create
@post = Post.new(
content: params[:post][:content]
type: get_type(params[:post][:content])
)
@post.save
end
def get_type
if self.content =~ /(\.jpg|\.png|\.bmp|\.gif)$/
return 'image'
end
end
型号:
def create
@post = Post.new(
content: params[:post][:content]
type: get_type(params[:post][:content])
)
@post.save
end
def get_type
if self.content =~ /(\.jpg|\.png|\.bmp|\.gif)$/
return 'image'
end
end
Giant免责声明:几天前我刚刚启动了ruby(以及rails):)您只需要调用模型:
def create
@post = Post.new(
content: params[:post][:content]
type: Post.get_type(params[:post][:content])
)
@post.save
end
并添加“self”关键字:
def self.get_type(content)
if content =~ /(\.jpg|\.png|\.bmp|\.gif)$/
return 'image'
end
end
但是我认为您应该在创建语句之前在中设置类型
:
class Post < ActiveRecord::Base
#...
before_create :set_type
#...
def set_type
if self.content =~ /(\.jpg|\.png|\.bmp|\.gif)$/
self.type = 'image'
end
end
end
class Post
您只需调用模型:
def create
@post = Post.new(
content: params[:post][:content]
type: Post.get_type(params[:post][:content])
)
@post.save
end
并添加“self”关键字:
def self.get_type(content)
if content =~ /(\.jpg|\.png|\.bmp|\.gif)$/
return 'image'
end
end
但是我认为您应该在创建语句之前在中设置类型
:
class Post < ActiveRecord::Base
#...
before_create :set_type
#...
def set_type
if self.content =~ /(\.jpg|\.png|\.bmp|\.gif)$/
self.type = 'image'
end
end
end
class Post
啊,太棒了!请您告诉我创建前的方法将做什么好吗?请看一下:简而言之,before\u create
允许您在创建对象(保存在数据库中,创建一个新条目)之前触发指定的方法(此处set\u type
)。有几个回调,比如保存前的,\u验证后的,等等。你可以连接到活动记录对象的生命周期中,还有一个有用的链接来获取Rails的指南:所以如果我在创建前使用,我不必在控制器中调用该方法吗?没错!set\u type
方法如果与before\u create一起使用,则每次创建新的Post对象时都会调用该方法(而不是在更新现有对象时:使用before\u update
或类似的方法)啊,太棒了!请您告诉我创建前的方法将做什么好吗?请看一下:简而言之,before\u create
允许您在创建对象(保存在数据库中,创建一个新条目)之前触发指定的方法(此处set\u type
)。有几个回调,比如保存前的,\u验证后的,等等。你可以连接到活动记录对象的生命周期中,还有一个有用的链接来获取Rails的指南:所以如果我在创建前使用,我不必在控制器中调用该方法吗?没错!set\u type
方法如果与before\u create一起使用,则每次创建新的Post对象时都会调用该方法(而不是在更新现有对象时:使用before\u update
或类似的方法)