I would like with Rails 4 to do a simple association beetween 3 models but i can't succeed to do that.
First model:Reader,Second model:Comments Third model : Books
The relation beetween the 3 models are:
class Book < ActiveRecord::Base has_many :comments
class Comment < ActiveRecord::Base belongs_to :book belongs_to :reader
class Reader < ActiveRecord::Base has_many :comments has_many :books, through: :comments
I have no problem for the relation Book has_many :comments but i have some problem with the relation Reader has_many :comments.
Field from CommentsTable : username, message and reader_id (for the has_many association). Field from ReaderTable : name , email.
I have a file _form.html.erb in view:
<%= form_for [@book, @comment] do |f| %>
<%= f.hidden_field :book_id %>
<%= f.text_field :reader_id, :placeholder => "reader id" %>
<br />
<%= f.text_area :message %>
<br />
<%= f.submit %>
<% end %>
And an other file _comment.html.erb:
<% if comment.reader_id != nil %>
<li><strong><%= link_to comment.reader.name, comment.reader %></strong></li>
<p><%= comment.message %></p>
<% end %>
Like you see i have a form with reader_id and message. When the user will enter this 2 informations, it will appears the reader.name (thanks to reader_id) and the comment.message. But i don't want that the user enter the integer "reader_id" (it has no sense) but directly the string "reader.name". How can i do that, knowing that after i will do a link_to on the reader.name to comment.reader ?
Please help me. Thank you.