سؤال

I have Model1, which has "has_many" rel with Model2. What I need is to create form for Model2 under each object on Model1 index page. Lets say I have Tweets and each tweet has form to add comments. I have troubles in understanding how to do it, how to get Tweet id on index page and so on.

هل كانت مفيدة؟

المحلول

Seems like all you need to do to get @comment form working under each @tweet on index page is:

- @tweets.each do |tweet|
  = tweet.name `#to show tweet`
  - tweet.comments.each do |comment| `#to show each tweet comment`
    = comment.content 
    = form_for [tweet, Comment.new] do |f| `#form forcomment belonging to this particular tweet`
     = f.text_field :content
     = f.submit

Hope it helps :)

نصائح أخرى

Let's say tweets has many comments, so create model Tweet and Comment with relationship also create controllers tweets and comments.

In your tweets/index page there are list of tweets, right and script is like this.

<% @tweets.each do |tweet| %>
 <%= link_to "show tweet", tweet_path(tweet) %>
<% end %>

show tweet link will take you to show page there you will get tweet id from params. Now you can make comment form in this show page as below

<%= form_for @comment do |f|%>
 <%= f.text_area :comment %>
 <%= f.submit %>
<% end %>

Routes file:

resources :tweets do
 resources :comments
end

I have just provided you some way to work by giving examples of rails-views, so check action in your controllers properly you will do it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top