如何通过HTML表单建立多个模型关联?
|
我想在网站上为“讨论”创建页面,并且在这些讨论页面上,用户可以撰写帖子。这些帖子需要属于讨论和用户,而讨论必须属于用户。
因此,我创建了两个模型,两个控制器和一个局部模型,以放入讨论显示页面。请注意,来自控制器的重定向只是以不合逻辑的方式分配给root_pages和其他用户,因为一旦表单生效,我想处理重定向。我没有附加用户模型,因为它很长,而且我认为没有必要。
我的问题是我无法让帖子控制器将正确的讨论ID分配给新帖子。我希望对此进行记录,以便将帖子与作者user_id(有效)和Discussion_id相关联。我知道使用@ post.discussion_id = @ discussion.id不能正确分配此值,但是我已经测试了@ post.discussion_id = 1以查看其余代码是否有效(确实可以)。
我该如何更改表单/控制器的设置以在此处分配Discussion_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 %>
没有找到相关结果
已邀请:
2 个回复
贸会
垫歌蝎降凤