我在rails上做了一个简单的博客.我有一个Post模型和一个Comment模型.当您创建评论时,如果评论无效,我想显示错误.我该怎么办?
模特邮报:
#/models/post.rb
class Post < ActiveRecord::Base
has_many :comments
validates :title, :content, :presence => true
end
Run Code Online (Sandbox Code Playgroud)
型号评论:
#/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :post
validates :name, :comment, :presence => true
end
Run Code Online (Sandbox Code Playgroud)
评论控制器
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end
end
Run Code Online (Sandbox Code Playgroud)
查看评论表:
<%= form_for([@post, @post.comments.build]) do |f| %>
<% if @comment.errors.any? %>
error!
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label …Run Code Online (Sandbox Code Playgroud) 我在Controller中有一个示例Action.
def some_action
product = Product.new
product.name = "namepro"
if product.save
client.update_attribute(:product_id,product.id)
end
end
Run Code Online (Sandbox Code Playgroud)
如何为此代码添加事务?我尝试使用此示例代码:
def some_action
**transaction do**
product = Product.new
product.name = "namepro"
if product.save
client.update_attribute(:product_create,Time.now)
end
**end**
end
Run Code Online (Sandbox Code Playgroud)
但它产生了这个错误:
undefined method `transaction'
Run Code Online (Sandbox Code Playgroud)
我读到在控制器中使用事务是一种不好的做法,但我不知道原因是什么(http://markdaggett.com/blog/2011/12/01/transactions-in-rails/)
在该示例中,如果已创建并保存产品并且客户端更新失败... Rails必须不执行任何操作.
谢谢.
我正在自定义default.ctp文件,我正在尝试在页面顶部显示当前登录的用户名.
在app_controller.php,我有以下内容:
function beforeFilter()
{
$user = $this->Auth->user();
if($user != null)
{
$this->Session->write('user_name',$user['User']['username']);
}
}
Run Code Online (Sandbox Code Playgroud)
在default.ctp,我有:
$user = $this->Session->read('Auth.User');
if(!empty($user))
{
echo 'Hello, ' . $user['user_name'];
}
Run Code Online (Sandbox Code Playgroud)
但是,似乎价值$user_name没有在任何地方设置.
我究竟做错了什么?有没有更好的方法来实现这一目标?
更新:我已按照答案中的说明对其进行了修改,但仍然无效.我收到一个错误:
未定义的索引:user_name [APP/views/layouts/default.ctp,第21行]
在我的应用程序中,我有一个Controller由main方法启动的.控制器初始化钩子,数据库连接,UI,另一个连接和其他东西.它占据了程序的大部分状态(不,它不是Singleton).在另一个例子中,有一个用于机器人的控制器,用于处理解释和发出命令.两者都是相当大的文件.
我已经阅读了上帝的对象,但我真的不知道如何将它分开.如果我将机器人中的解释器和调度员分开,它将会形成一个可怕的调用链(类似于getBot().getParser().getOutput().sendMessage(recipient, message)).类似地,在第一个控制器中,如果我分开,你将只有包含字段的数据对象和一些别名实用程序方法.将它们拆分会让事情变得更糟.在你认为它不可维护之前,实际上并非如此.我甚至没有写Bot控制器,但我仍然知道发生了什么.
但问题是Bot类是2000行(如果我拿出Javadoc注释可能会更短)并且Bot大约是1000行.很多行=上帝的对象.但是对于项目的一个或两个核心类是否可以?
想想一个简单的Rails脚手架应用程序,其中包含一个表单,用于通过"保存"按钮将记录添加到数据库中.在"创建"操作之后,控制器重定向到"显示"操作,用户可以使用"编辑"链接编辑刚刚插入的记录.到目前为止,这么简单.
但是,如果用户在创建记录后使用浏览器的后退按钮返回"新"操作,则浏览器会显示包含用户刚刚输入的值的表单.现在他改变了一些值并再次按下"保存".他认为这会改变记录,但当然这会创造一个新记录.
防止此类重复条目的首选方法是什么?我正在寻找一个通用的解决方案,可能基于cookie或JavaScript.
Spring 3 MVC处理多个表单提交控制器.
我正在开发具有多种形式的JSP页面.1)搜索客户,2)搜索产品,3)打印东西等我有一个不同的表单绑定对象绑定到每个表单,我的控制器代码看起来类似于下面
@Controller
@RequestMapping(value="/search.do")
public class SearchController {
@RequestMapping(method = RequestMethod.GET)
public String pageLoad(ModelMap modelMap) {
modelMap.addAttribute("productSearch", new ProductSearchCriteria());
modelMap.addAttribute("customerSearch", new CustomerSearchCriteria());
modelMap.addAttribute("print", new PrintForm());
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView searchProducts(@ModelAttribute("productSearch") ProductSearchCriteria productSearchCriteria,
BindingResult result, SessionStatus status) {
//Do Product search
return modelAndView;
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView searchCustomers(@ModelAttribute("customerSearch") CustomerSearchCriteria customerSearchCriteria,
BindingResult result, SessionStatus status) {
//Do Customer search
return modelAndView;
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView printSomething(@ModelAttribute("print") PrintForm printForm,
BindingResult result, SessionStatus status) {
//Print …Run Code Online (Sandbox Code Playgroud) 对于URL重定向,我需要在控制器中翻译某些内容.
我如何访问$ this-> translate(); 在控制器?
谢谢!缺口
我正在创建一个网站,用户将填写文本区域(回答问题),然后按下一步.当他们按下时,textarea将被提交给控制器,下一个问题将被检索(我也将答案存储在cookie中).不幸的是,当我在调试中运行代码时,我意识到textarea没有被提交b/c参数为null.我试图解决它,我环顾四周,似乎正在做得很好.希望这是一个简单的解决方案.非常感谢你的时间!
控制器:
// POST: /Question/1
[HttpPost]
public ActionResult q(string textAnswer) {
if (textAnswer != null)
ViewBag.current++;
Question q = db.Questions.Find(ViewBag.current);
if (q == null) {
return RedirectToAction("submit");
}
return View(q);
}
Run Code Online (Sandbox Code Playgroud)
视图:
<form class="form-horizontal" id="myForm" method="post" enctype="text/plain" name="input">
<p>
<h3>Question <span id="integer">@ViewBag.current</span></h3>
@Html.DisplayFor(model => model.Ques)
</p>
<div class="control-group">
<label class="control-label">Answer</label>
<div class="controls">
<textarea rows="20" style="width:600px" id="textAnswer"></textarea>
</div>
</div>
<div class="control-group">
<div class="controls" >
<button onclick="history.back()" type="button" class="btn">Back</button>
<input type="submit" class="btn" value="Next" />
</div>
</div>
</form>
Run Code Online (Sandbox Code Playgroud) 尝试将数据添加到scrapbook_entries的联接表中,其中包含has_one:scrapbook和has_one:recipe.
:食谱和:剪贴簿已经存在.我正在尝试添加它们以将它们与scrapbook_entries表链接.
form_for添加到scrapbook_entries表:
<%= form_for(@scrapbook_entry, :url => scrapbook_entries_path(params[:id])) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%=f.select(:scrapbook_id, current_user.scrapbooks.collect {|p| [ p.name, p.id ] }, {prompt: 'Select Scrapbook...'})%>
<%= f.hidden_field :recipe_id, :value => @recipe.id %>
</div>
<%= f.submit "Save", class: "btn btn-large btn-primary" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
scrapbook_entries_controller:
def create
@recipe = Recipe.find(params[:scrapbook_entry][:recipe_id])
@scrapbook = current_user.scrapbooks.find(params[:scrapbook_entry][:scrapbook_id])
@entry = @scrapbook.scrapbook_entries.build(scrapbook: @scrapbook)
if @entry.save
flash[:success] = "Added '#{@recipe.name}' to scrapbook '#{@scrapbook.name}'"
else
flash[:error] = "Could not add to scrapbook"
end …Run Code Online (Sandbox Code Playgroud) 我正在从这里学习Sitecore中的Controller渲染.
我创建了一个简单的控制器(HelloWorld)和相关视图(Index.schtml).在Sitecore Explorer的渲染部分中映射它(使用Name PageContent)并在Sitecore Explorer的内容部分中的Home Item中添加渲染项目.但是当我浏览它时,它会给出错误.
The controller for path '/' was not found or does not implement IController.
Run Code Online (Sandbox Code Playgroud)
我读过的所有帖子都与Asp .Net MVC有关..但我有与Sitecore MVC有关的问题
Sample.html(Sitecore Explorer渲染部分中的页面内容)
@using Sitecore.Mvc
<html>
<body>
@Html.Sitecore().Placeholder("content")
<p>Today's date is @DateTime.Now.ToShortDateString()</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
只有这条线给出了问题
@Html.Sitecore().Placeholder("content")
Run Code Online (Sandbox Code Playgroud)
如果我删除此行...它工作正常,浏览器上的页面显示日期和时间
的index.html
<p>Hello from Controller -todays Date is @DateTime.Now.ToString()</p>
Run Code Online (Sandbox Code Playgroud)
调节器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC.Controllers
{
public class HelloWorldController : Controller
{
//
// GET: /HellowWorld/
public ActionResult Index()
{
return View();
} …Run Code Online (Sandbox Code Playgroud) controller ×10
.net ×1
asp.net-mvc ×1
browser ×1
c# ×1
cakephp ×1
crud ×1
god-object ×1
java ×1
java-ee ×1
join ×1
model ×1
models ×1
post ×1
ruby ×1
sitecore ×1
sitecore-mvc ×1
spring-mvc ×1
transactions ×1
translation ×1