【问题标题】:How can i make multiple model associations through an html form?如何通过 html 表单进行多个模型关联?
【发布时间】:2011-06-14 19:42:59
【问题描述】:

我想在网站上创建讨论页面,并且用户可以在这些讨论页面上写帖子。帖子需要属于讨论和用户,讨论需要属于用户。

因此,我创建了两个模型、两个控制器和一个部分以放在讨论显示页面上。请注意,来自控制器的重定向只是以不合逻辑的方式分配给 root_pages 和其他人,因为我想在表单工作后处理重定向。我没有附上用户模型,因为它很长,我认为没有必要。

我的问题是我无法让帖子控制器为新帖子分配正确的讨论 ID。我希望将其记录下来,以便帖子与作者 user_id(有效)和讨论 ID 相关联。我知道使用 @post.discussion_id = @discussion.id 不会正确分配它,但我已经测试了 @post.discussion_id = 1 以查看其余代码是否有效(确实如此) .

如何更改表单/控制器的设置以在此处分配讨论 ID?任何帮助将不胜感激!

讨论控制器:

class DiscussionsController < ApplicationController
  def show
    @discussion = Discussion.find(params[:id])
    @title = @discussion.title
    @post = Post.new if signed_in?
  end

结束

讨论模型:

class Discussion < ActiveRecord::Base
  attr_accessible :title, :prompt
  belongs_to :user

  validates :title, :presence => true, :length => { :within => 5..100 }
  validates :prompt, :presence => true, :length => { :within => 5..250 }
  validates :user_id, :presence => true
  has_many :posts, :dependent => :destroy

 default_scope :order => 'discussions.created_at DESC'
end

后控制器:

class PostsController < ApplicationController
  def create
    @post = current_user.posts.build(params[:post])

    @post.discussion_id = @discussion.id
    if @post.save
      redirect_to discussion_path
    else
      redirect_to user_path
    end
  end

结束

帖子模型:

class Post < ActiveRecord::Base
  attr_accessible :content

  validates :content, :presence => true, :length => { :maximum => 10000 }
  validates :user_id, :presence => true
  validates :discussion_id, :presence => true
  belongs_to :user
  belongs_to :discussion

  default_scope :order => 'posts.created_at ASC'
end

部分用于帖子形式:

<%= form_for @post do |f| %>
<%= render 'shared/error_messages' %>
<div class="field">
    <%= f.text_area :content, :class => "inputform largeinputform round" %>
</div>

<div class="actions">
    <%= f.submit "Post", :class => "submitbutton round" %>
</div>
<% end %>

【问题讨论】:

    标签: ruby-on-rails associations forms


    【解决方案1】:

    您的问题是您没有将@discussion 放入后控制器的机制一种方法可能是将讨论 id 放在部分表单的隐藏字段中,然后在控制器中将其作为参数读取。

    兰斯

    【讨论】:

    • 是的,我试过了,它确实有效——只是我必须在 post 模型中将 :discussion_id 添加到 attr_accessible 中。我认为这不太安全,所以我想知道是否有另一种方法可以让 @discussion 进入后期控制器?
    【解决方案2】:

    在 PostsController 中,您没有在 create 方法中创建 @discussion。

    【讨论】:

    • 好的,但我尝试将 @discussion = Discussion.find(params[:id]) 放入其中,但这不起作用。错误是“找不到没有 ID 的讨论”。有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 2017-05-22
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    相关资源
    最近更新 更多