SQLite3::SQLException: no such column: problem with association and show view
I am getting the following error message on the view : http://localhost:3000/microposts/2 SQLite3::SQLException: no such column: answers.micropost_id: SELECT "answers".* FROM "answers" WHERE ("answers".micropost_id = 2)
Here are my migrations:
| db > migration > create micropost |
class CreateMicroposts < ActiveRecord::Migration
def self.up
create_table :microposts do |t|
t.string :content
t.timestamps
end
end
def self.down
drop_table :microposts
end
end
| db > migration > create answer |
class CreateAnswers < ActiveRecord::Migration
def self.up
create_table :answers do |t|
t.string :location
t.text :body
t.references :micropost
t.integer :micropost_id
t.timestamps
end
end
def self.down
drop_table :answers
end
end
The Answer Controler :
def create
@answer = Answer.new(params[:answer])
@answer.micropost = @micropost; @answer.save && @micropost.save
redirect_to micropost_path(@micropost)
respond_to do |format|
if @answer.save
format.html { redirect_to(@answer, :notice => 'Answer was successfully created.') }
format.xml { render :xml => @answer, :status => :created, :location => @answer }
else
format.html { render :action => "new" }
for开发者_运维百科mat.xml { render :xml => @answer.errors, :status => :unprocessable_entity }
end
end
end
and the View:
<p id="notice"><%= notice %></p>
<p>
<b>Content:</b>
<%= @micropost.content %>
<h2>Location Answers:</h2>
<% @micropost.answers.each do |answer| %>
<p>
<b>Answer:</b>
<%= answer.body%>
</p>
<%end %>
<h2> Answer a location:</h2>
<%= form_for ([@micropost, @micropost.answers.build]) do |f| %>
<div class="field">
<%= f.label :location %><br />
<%= f.text_field :location %>
</div>
<div class="field">
<%= f.label :body %><br/>
<%= f.text_area :body %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
</p>
<%= link_to 'Edit', edit_micropost_path(@micropost) %> |
<%= link_to 'Back', microposts_path %>
I cannot find what's wrong in this application. - I tried to rollback and migrate again it didn't work. - I tried to manually add the "t.integer :micropost_id" in the migration it didn't work My model have the association 'belongs_to" and "has_many" and I added " resources :microposts do resources :answers end to my config.rb file.
I believe the has_many association requires a relationship table to join against. If you had has_one and belongs_to (a one to one association) works with the simple _id column approach but has_many won't. So if you put this join table in and describe the has_many through it, you should get what you want.
Here's a really great guide for rails associations that I use when this stuff becomes unclear to me.
You don't need to set micropost_id in your migration. This is done by t.references
create_table :answers do |t|
t.string :location
t.text :body
t.references :micropost
t.timestamps
end
Best practice to set and index, for example:
add_index :answers, :micropost_id
精彩评论