Ruby on rails 2 level model
- by jony17
I need some help creating a very simple forum in a existing model.
What I want in a Game page, have a mini forum, where is possible create some topics and some comments to this topics. In the beginning I'm only implement topics.
This is the error I have:
Mysql2::Error: Column 'user_id' cannot be null: INSERT INTO `topics` (`game_id`, `question`, `user_id`) VALUES (1, 'asd', NULL) 
This is my main model:
game.rb
class Game < ActiveRecord::Base
   attr_accessible :name
   validates :user_id, presence: true
   validates :name, presence: true, length: { maximum: 50 }
   belongs_to :user
   has_many :topics, dependent: :destroy
end
topic.rb
class Topic < ActiveRecord::Base
     validates_presence_of :question
     validates_presence_of :game_id
     attr_accessible :question, :user_id
     validates :question, length: {maximum: 50}, allow_blank: false
     belongs_to :game
     belongs_to :user
end
topic_controller.rb
def create
    @game = Game.find(params[:game_id])
    @topic = @game.topics.create(params[:topic])
    @topic.user_id = current_user.id
    respond_to do |format|
      if @topic.save
        format.html { redirect_to @game, notice: 'Topic was successfully created.' }
      else
        format.html { render action: "new" }
      end
    end
end
game/show.html.erb
<h2>Topics</h2>
<% @game.topics.each do |topic| %>
    <p>
      <b>Question:</b>
      <%= topic.question %>
    </p>
<% end %>
<h2>Add a topic:</h2>
<%= form_for([@game, @game.topics.build]) do |f| %>
    <div class="field">
     <%= f.label :question %><br />
      <%= f.text_field :question %>
    </div>
    <div class="actions">
      <%= f.submit %>
    </div>
<% end %>
Thanks ;)