【问题标题】:Two forms, two models, one view ROR两种形式,两种模式,一种观点ROR
【发布时间】:2014-09-13 15:43:22
【问题描述】:

我正在尝试在同一个视图中为两个不同的模型制作两个表单。

我有一个名为 category 的模型和一个名为 post 的模型。 我试图在同一视图中为类别制作表格,我有一个帖子表格。 帖子的表单工作正常,但是当我尝试为类别添加表单时,我收到此错误: Category::ActiveRecord_Relation:Class 的未定义方法 `model_name'

category.rb - 模型

has_many :posts

post.rb - 模型

has_many :categories

posts_controller

def index
@posts = new.Post
@categories = new.Category
end

def create
@posts = Post.create(post_params)
@posts.save
redirect_to :back
end

def create_cate
@categories = Categroy.create(categories_params)
@categroies.save
redirect_to :back
end

帖子视图 - index.html.erb

<%= form_for(@posts) do |f| %>
<%= f.text_field :title %>
<%= f.text_area :content %>
<%= f.submit %>
<% end %>

<%= form_for(@categories) do |f| %>
<%= f.text_field :name %>
<%= f.submit %>
<% end %>

routes.rb

resources :posts
resources :categories
root 'posts#index'

我试过搜索if,但我只能找到两种模型,一种形式的解决方案。

提前致谢。 :-)

【问题讨论】:

    标签: ruby-on-rails ruby forms ruby-on-rails-4 models


    【解决方案1】:

    既然你在索引动作中说它:

    def index
      @post = Post.new
      @category = Category.new
    end
    

    在你看来:

    <%= form_for(@post) do |f| %>
      <%= f.text_field :title %>
      <%= f.text_area :content %>
      <%= f.submit %>
    <% end %>
    
    <%= form_for(@category) do |f| %>
      <%= f.text_field :name %>
      <%= f.submit %>
    <% end %>
    

    【讨论】:

    • 根据Sandi's rule,这种方法是错误的 - 控制器只能实例化一个对象。因此,视图只能知道一个实例变量,并且视图应该只向该对象发送消息。
    • @ArupRakshit 规则是为了让你三思而后行,它们不是为了阻止你做生意
    • @apneadiving 不。这不是一个好主意。我对你的方法感觉不舒服。
    猜你喜欢
    • 2011-09-28
    • 2014-04-12
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 2011-02-03
    相关资源
    最近更新 更多