0
votes

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.

1

1 Answers

0
votes

I'm guessing the reader is the user. If it is, then you'll probably want to have a whole authentication system (maybe think about Devise) and just assign the comment to the current user within the controller. You'll also want to assign the book in the controller.

EDIT:

Devise will make available a current_user method in your controller. So your create method in your comments controller should look like this:

def create
    comment = current_user.comments.new(comment_params)
end

You don't need to assign the reader.name to comments. That's what the association is for. You can do comment.reader.name, or better yet, use delegate (look that up) and do comment.reader_name.