I am quite new to rails and I have a bit of trouble understanding associations. I want to make a fast forum(just the thread - post mechanism nothing else) . My models are generated by :
1. rails generate scaffold Forumthread title:string
2. rails generate scaffold Forumpost title:string content:text username:string
In my models I added the associations namely:
class Forumthread < ActiveRecord::Base
has_many :forumposts, dependent: :destroy
end
class Forumpost < ActiveRecord::Base
belongs_to :forumthread
end
On the show page of a thread I want to be able to make a forumpost for that thread . I am trying to do it like this : view: <%= notice %>
<p>
<strong>Title:</strong>
<%= @forumthread.title %>
</p>
<% form_for(@post) do |f| %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<div class="field">
<%= f.label :username %><br>
<%= f.text_field :username %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<%= link_to 'Edit', edit_forumthread_path(@forumthread) %> |
<%= link_to 'Back', forumthreads_path %>
and controller:
def show
@current_thread = Forumthread.find_by_id(params[:id])
@post = @current_thread.forumposts.build
end
I didn't get to the create part because it seems it doesn't work just typing @current_thread.forumposts.build
to create an object. What am I missing ?
I want @post to be an object of type forumpost so I can create with @current_thread.forumposts.create(forumposts_params)
;
At the moment I get the following error:
undefined method `val' for #<Arel::Nodes::BindParam:0x007fe5c0648770>
I will happily provide more data if it is requested! .
I remember reading about this error occuring when foreign_key
is missing (https://github.com/rails/rails/commit/78bd18a90992e3da767cfe492f1bc5d63077da8a) and it looks like this might be your case, since you didn't included it when genereting scaffold for Forumpost. Do you have forumthread_id
column in your database table for Forumposts? If you don't know what I'm talking about - go to db/schema.rb file and and check if you can see something like:
create_table "forumsposts", force: true do |t|
#some other fields
t.integer "forumthread_id", null: false
#some other fields
end
If not, you will have to generate and run one more migration adding this missing foreign_key
to Forumspost. Read about it on http://guides.rubyonrails.org/association_basics.html#options-for-belongs-to-foreign-key :), run rails generate migration AddForumthreadIdToForumpost
, put something like the code below in newly created migration file and run rake db:migrate
:
class AddForumthreadIdToForumpost < ActiveRecord::Migration
def change
add_column :forumposts, :forumthread_id, :integer, null: false
add_index :forumposts, :forumthread_id
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With