开发者

Why can't I build more than one nested attribute here?

this is my form code:

<%= simple_form_for setup_video(@video) do |f| %>
<% f.fields_for :comment_titles do |t| %>
    <%= t.input :title, :label => "Comment Title:" %>
    <%= t.button :submit, :value => 'Add', :id => 'add_comment_title' %>
        <div class='hint'>Let your listeners know what comments you want by adding a guiding title for them. Pose a question, ask for feedback, or anything else!</div> 
<% end %>
<% end %>

I have has_many :comment_titles and accepts_nested_attributes_for :comment_titles, :comments in my model. when I create a new comment_title in the form, the old one is replaced. I want an additional one to be built. How can I do this?

Here are the video controller actions:

def new
  @video = Video.new
  respond_to do |format|
      format.js do
         render_to_facebox(:partial => 'add_video')
      end
  end
end

def create
  @video = current_user.videos.new(params[:video])

  respond_to do |format|
    if @video.save
      format.html { redirect_to(@video) }
    else
      format.html { render :action => "new" }
    end
  end
end

I think this is actually what is needed:

def update
 开发者_运维知识库 @video = current_user.videos.find(params[:id])

  respond_to do |format|
    if @video.update_attributes(params[:video])
      format.html { redirect_to(@video) }
      format.js
    else
      format.html { render :action => "edit" }
    end
  end
end


The edit action here will provide a form which will allow you to edit the existing record as well as its nested attributes. This is why it's replacing the existing object.

If you only want people to add new comment titles then I would recommend building a new object in your edit action like this:

def edit
  video = current_user.videos.find(params[:id])
  video.comment_titles.build
end

Then this will be available as an additional row in your fields_for call. To only make this show new objects:

<% f.fields_for :comment_titles do |t| %>
  <% if t.object.new_record? %>
    # stuff goes here
  <% end %>
<% end %>

However this restricts people to being able to only add new items in an edit action, which may seen counter-intuitive to some users.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜