0
我有一個公告'has_many'評論和評論'belongs_to'公告關係。 在我的根目錄中,我在每個循環中顯示公告,並且我嘗試在每個新聞下發表評論form_for。rails 4如何在form_for中傳遞object_id?
我root_path行動:
def home
@announcements = Announcement.page(params[:page]).order('id DESC')
end
這裏是我的通告循環:
<% @announcements.each do |announcement| %>
.
.
.
<div class="create_comment form-inline">
<%= form_for(announcement.comments.build) do |form| %>
<%= form.label :author, "Autor:" %>
<%= form.text_field :author, class: "form_control" %>
<%= form.label :content, "Treść:" %>
<%= form.text_field :content, class: "form_control" %>
<%= form.submit "Dodaj!", class: "btn btn-primary", url: comments_path %>
<% end %>
</div>
</div>
<% end %>
這裏是我的評論創建行動:
def create
@announcement = Announcement.find(params[:comment_id])
@comment = @announcement.comments.new(comments_params)
if @comment.save
flash[:success] = "Komentarz dodano"
redirect_to root_path
else
render 'static_pages/home'
end
end
private
def comments_params
params.require(:comment).permit(:author,:content)
end
但我得到一個錯誤:Couldn找不到公告ID
我知道我可以使用hidden_field並將其傳遞給comments_params,但這不是安全的解決方案。
我剛開始我的Rails冒險,所以如果有人知道我的錯誤在哪裏,請嘗試做出完整的解釋。