2015-07-13 2 views
2

В новой форме темы есть поля для заголовка, описания и первого опубликованного контента.Сохранение: содержание первого сообщения о создании темы, с моделями сообщений и темы

При представлении необходимо создать тему со значениями для названия, описания, идентификатора пользователя и идентификатора форума, а также сообщения со значениями для содержимого, идентификатора пользователя и идентификатора темы. Однако содержимое post: содержимое не сохраняется в таблице, хотя идентификатор пользователя и идентификатор темы.

просмотров/темы/_form.html.erb

<%= form_for(@topic) do |f| %> 
    <% if @topic.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@topic.errors.count, "error") %> prohibited this topic from being saved:</h2> 

     <ul> 
     <% @topic.errors.full_messages.each do |message| %> 
     <li><%= message %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    <% if params[:forum] %><input type="hidden" id="topic_forum_id" name="topic[forum_id]" value="<%= params[:forum] %>" /><% end %> 
    <div class="field"> 
    <%= f.label :title %><br> 
    <%= f.text_field :title %> 
    </div> 
    <div class="field"> 
    <%= f.label :description %><br> 
    <%= f.text_area :description %> 
    </div> 
    <div class="field"> 
    <textarea name="post[content]" class="form-control" cols="80" rows="20"><%= @post.content %></textarea> 
    </div> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

Контроллеры/topics_controller.rb

def new 
    @topic = Topic.new 
    @post = Post.new 
end 

def create 
    user_id = current_user.id || 1 # temporary assignment until guest account generated 
    @topic = Topic.new(title: params[:topic][:title], description: params[:topic][:description], forum_id: params[:topic][:forum_id], user_id: user_id) 
    if @topic.save 
    @post = Post.new(content: params[:post][:content], topic_id: @topic.id, user_id: user_id) 
    if @post.save 
     flash[:notice] = "Successfully created topic." 
     redirect_to "/topics/#{@topic.id}" 
    else 
     render action: 'new' 
    end 
    else 
    render action: 'new 
    end 
end 

модели/post.rb

class Post < ActiveRecord::Base 
    belongs_to :topic 
    belongs_to :user 

    has_many :replies, :dependent => :nullify 

    validates :content, presence: true 

    attr_accessor :content 
end 

модели/topic.rb

class Topic < ActiveRecord::Base 
    belongs_to :forum 
    belongs_to :user 

    has_many :posts, :dependent => :destroy 

    validates :title, presence: true, length: { maximum: 255 } 
    validates :user_id, presence: true 
    validates :forum_id, presence: true 
end 
+0

Можете ли вы разместить полную форму? – Pavan

+0

Обновлено с полной формой. Это очень просто. – Kalyn

+0

Можете ли вы также опубликовать журнал параметров, созданный при отправке формы? – Pavan

ответ

0

Я бы применил концепцию accepsts_nested_attributes, как показано ниже, чтобы справиться с вашей ситуацией.

#topic.rb 

class Topic < ActiveRecord::Base 
    belongs_to :forum 
    belongs_to :user 

    has_many :posts, :dependent => :destroy 
    accepts_nested_attributes_for :posts 
    validates :title, presence: true, length: { maximum: 255 } 
    validates :user_id, presence: true 
    validates :forum_id, presence: true 
end 

#topics_controller.rb 

def new 
    @topic = Topic.new 
    @post = @topic.posts.build 
end 

def create 
    user_id = current_user.id || 1 # temporary assignment until guest account generated 
    @topic = Topic.new(params[:topic]) 
    if @topic.save 
    @post = Post.new(params[:post]) 
    @post.topic_id = @topic.id 
    @post.user_id = user_id 
    if @post.save 
     flash[:notice] = "Successfully created topic." 
     redirect_to @topic 
    else 
     render action: 'new' 
    end 
    else 
    render action: 'new' 
    end 
end 

#form 
<%= form_for(@topic) do |f| %> 
    <% if @topic.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@topic.errors.count, "error") %> prohibited this topic from being saved:</h2> 

     <ul> 
     <% @topic.errors.full_messages.each do |message| %> 
     <li><%= message %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    <% if params[:forum] %><input type="hidden" id="topic_forum_id" name="topic[forum_id]" value="<%= params[:forum] %>" /><% end %> 
    <div class="field"> 
    <%= f.label :title %><br> 
    <%= f.text_field :title %> 
    </div> 
    <div class="field"> 
    <%= f.label :description %><br> 
    <%= f.text_area :description %> 
    </div> 
    <%= f.fields_for @post do |p| %> 
    <div class="field"> 
    <%= p.text_area :content, cols: 80, rows: 20, class: "form-control" %> 
    </div> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 
Смежные вопросы