Rails/ActiveRecord has_many question
I am using Ruby 1.8.7 and Rails 2.3.5
So I am trying to figure out why my has_many association doesn't work properly. I have 2 tables in the database, Videos and Comments. Inside the Comments table I have a foreign key of video_id column and when posting a comment nothing shows up on my video's page because the video_id column is NULL so nothing got posted.. If I add the id of the video in the video_id column, you can view the comment. Am I missing something?
Video.rb
class Video < ActiveRecord::Base
has_many :comments
end
Comment.rb
class Comment < ActiveRecord::Base
belongs_to :video
end
comments_controller.rb
def create
@comment = Comment.new(params[:comment])
@comment.video_id = params[:video_id]
if @comment.save
flash[:notice] = 'Your comment was saved!'
else
flash[:notice] = 'Sorry, there was a problem.'
end
redirect_to videos_path
end
_form.html.erb
<% form_for :comment, :url => comments_path(@video) do |f| %>
<p>
<%= f.label :name, "Your Name" %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :body, "Your Comment" %>
<%= f.text_field :body %>
</p>
<p>
<%= f.submit "Submit", :disable_with => 'Submiting...' %>
</p>
<% end -%>
Routes.rb
ActionController::Routing::Routes.draw do |map|
map.index '/', :controller => 'homepage', :action => 'index'
map.logout '/logout', :controller => 'sessions', :action => 'destroy'
map.signout '/signout', :controller => 'sessions', :action => 'destroy'
map.login '/login', :controller => 'sessions', :action => 'new'
map.signin '/signin', :controller => 'sessions', :action => 'new'
map.register '/register', :controller => 'users', :action => 'create'
map.signup '/signup', :controller => 'users', :action => 'new'
map.activate '/activate/:activation_code', :co开发者_JAVA技巧ntroller => 'users', :action => 'activate', :activation_code => nil
map.resources :users
map.resource :session
map.resources :comments
map.resources :videos
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
You're not specifying params[:video_id]
correctly.
From what I can tell you want to allow users to comment on videos?
If so, I believe the real routing structure you want is:
resources :videos do
resources :comments
end
This will make a path like video_comments_path(@video)
which you can POST to and in the create action do something like:
@video = Video.find(params[:video_id])
@comment = @video.comments.create(params[:comment])
Thats basically it
You could use a nested resource (I think they are there in 2.3.5, not sure).
Or else you could modify your partial to pass the video_id parameter:
_form.html.erb
<% form_for :comment, :url => comments_path(@video) do |f| %>
<%= hidden_field_tag 'video_id', @video.id %>
<p>
<%= f.label :name, "Your Name" %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :body, "Your Comment" %>
<%= f.text_field :body %>
</p>
<p>
<%= f.submit "Submit", :disable_with => 'Submiting...' %>
</p>
<% end -%>
精彩评论