“Def create”手动导轨
有什么方法可以手动执行“创建”功能吗? 我有一个脚手架(模型/控制器/视图),所以我想做的就是稍微改变用户给我的参数。
def create
@meme = Meme.new(params[:meme])
respond_to do |format|
if @meme.save
format.html { redirect_to @meme, notice: 'Meme was successfully created.' }
format.json { render json: @meme, status: :created, location: @meme }
else
format.html { render action: "new" }
format.json { render json: @meme.errors, status: :unprocessable_entity }
end
end
end
有没有办法做类似的事情:
def create
@meme = Meme.new
@meme.name = params([:name])
@meme.id = params([:id])
@meme.url = @[email protected]
respond_to do |format|
if @meme.save
format.html { redirect_to @meme, notice: 'Meme was successfully created.' }
format.json { render json: @meme, status: :created, location: @meme }
else
format.html { render action: "new" }
format.json { render json: @meme.errors, status: :unprocessable_entity }
end
end
end
所以正如你在最后一个例子中看到的,我想保存一个连接名称和ID的URL, 有什么方法可以从控制器实现这一点吗?
提前致谢。
Is there any way on manually doing the "create" function?
I have an scaffold, (model/controller/view), so what I want to do is to change a little bit the parameters that the user gave me.
def create
@meme = Meme.new(params[:meme])
respond_to do |format|
if @meme.save
format.html { redirect_to @meme, notice: 'Meme was successfully created.' }
format.json { render json: @meme, status: :created, location: @meme }
else
format.html { render action: "new" }
format.json { render json: @meme.errors, status: :unprocessable_entity }
end
end
end
Is there any way of doing something like:
def create
@meme = Meme.new
@meme.name = params([:name])
@meme.id = params([:id])
@meme.url = @[email protected]
respond_to do |format|
if @meme.save
format.html { redirect_to @meme, notice: 'Meme was successfully created.' }
format.json { render json: @meme, status: :created, location: @meme }
else
format.html { render action: "new" }
format.json { render json: @meme.errors, status: :unprocessable_entity }
end
end
end
So as you can see in the last example I want to save a URL concatenating the name and the id,
is there any way of achieving this from the controller.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在寻找的代码是两个示例的组合:
我在名称和 ID 之间添加了破折号,只是为了好玩。
您可能还想考虑在 Meme 模型内的
before_save
挂钩中执行此操作,这将是比在控制器中使用它更干净的解决方案。祝你好运!The code you are looking for is kind of a combination of both of your samples:
I threw in a dash between the name and the id just for kicks.
You might also want to think about doing this in a
before_save
hook inside the Meme model, that would be a cleaner solution than having it in the controller. Good luck!