Ruby on rails 2 level model
Posted
by
jony17
on Stack Overflow
See other posts from Stack Overflow
or by jony17
Published on 2012-11-18T10:34:56Z
Indexed on
2012/11/18
11:00 UTC
Read the original article
Hit count: 156
ruby-on-rails
|ruby
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 ;)
© Stack Overflow or respective owner