ruby on rails - How to add a record -


im studying ruby on rails , found 1 question can't resolve.

description: have ticket , comments. 1 ticket should have many comments. comments belong ticket should listed in ticket's "show" view. there text field , button "add new comment". after adding comment should rendered view "show" of current ticket.

the problem: how send current ticket's id comments model saved comment , how render (or redirect?) view "show" of ticket comment's method "create"?

my files:

class ticket < activerecord::base   has_many :comments end 

class comment < activerecord::base   belongs_to :ticket end 

class ticketscontroller < applicationcontroller   def show     @ticket = ticket.find(params[:id])     @comment = comment.new   end ...... 

class commentscontroller < applicationcontroller   def create     @comment = comment.new(params.require(:comment).permit(:text))     **@comment.ticket_id = @current_ticket_id** #the problem here     @comment.save      **redirect_to ticket_path(params[:id])** #and here   end 

<h1>ticket details</h1>  <%= @ticket.number %></br> <%= @ticket.title %></br> <%= @ticket.text %></br>  <h3>comments:</h3> <%= form_for(@comment) |f| %> <%= f.label "your comment:" %> <%= f.text_field :text %> <%= f.submit %> <% end %>  </br>  <% @ticket.comments.all.each |comment| %> <p><%= comment %></p> <% end %> 

you pass ticket id hidden field in form, follows:

<%= form_for(@comment) |f| %>   <%= f.label "your comment:" %>   <%= f.text_field :text %>   <%= f.hidden_field :ticket_id, value: @ticket.id %>   <%= f.submit %> <% end %> 

then access controller follows:

@comment.ticket_id = params[:ticket_id] 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -