如何在另一个模型中创建名称空间的类的实例

时间:2015-03-08 00:51:01

标签: ruby-on-rails ruby form-for

resources :recipes do
  resource :like, module: :recipes
  resources :comments, only: [:new, :create, :show, :index], module: :recipes
end

recipe_comments GET    /recipes/:recipe_id/comments(.:format) recipes/comments#index
               POST   /recipes/:recipe_id/comments(.:format)  recipes/comments#create

Comments are in /recipes/:id
Recipe Controller

def show
   @recipe = Recipe.find(params[:id])
   @comment = @recipe.comments.new
   @clean_recipe = Sanitizer.new(@recipe)
end

Recipes::CommentsController

Theres a before action that finds recipe.

 def create
    @comment = @recipe.comments.new(comment_params)
    @comment.user_id = current_user.id
    if @comment.save
        redirect_to recipes_path
    end
end

我已经完成了

   form_for([@article,@comment]) and form_for [@article,Comment.new] 

并且评论仍未保留。我想知道因为模块命名空间,我是否必须做一些不同的事情?

2 个答案:

答案 0 :(得分:1)

在创建操作中添加logger.info 'I am inside create action in comments controller'。如果您在rails控制台中看到此记录器消息,则会调用create动作。这意味着您的路由已正确定义,您的表单使用正确的表单帮助程序。

答案 1 :(得分:0)

正确的格式是form_for([@ recipe,@ comment])但是,我在评论模型中进行了长度验证,但未通过。我设置了too​​_short和too_long消息,但是它们没有出现,这进一步让我感到困惑