i´m a newbie to rails and have a problem with my associated object not being saved. I think I did everything the way it should be done and I can´t figure out, why it isn´t working. So thanks in advance for everyone who can help me get a little closer to solving this problem. These are my models :

class Examdate < ActiveRecord::Base
  belongs_to :exam
  attr_accessible :date, :exam_id
end
class Exam < ActiveRecord::Base
  attr_accessible :title, :prof_id, :deadline
  belongs_to :prof
  has_many :examdates, :dependent => :destroy
  accepts_nested_attributes_for :examdates
end

In my exams_controller I have this:

def new
    @exam = Exam.new
    3.times{@exam.examdates.build()}
end
def create
    @exam = Exam.new(params[:exam])
    respond_to do |format|
      if @exam.save 
      ....

Now in my view I have the semantic_fields_for method, I also tried it with normal fields_for and got the same result:

<%= semantic_form_for @exam do |f| %>
<% if @exam.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@exam.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @exam.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
<% end %>   
<%= f.inputs do%>
<%= f.input :title%>
<%= f.input :prof%> 
<%= f.input :deadline, :start_year => Time.now.year, :label => "Anmeldefrist"%>
 <% end %>  
<%= f.semantic_fields_for :examdates do |builder|%>
    <%= render "examdates_fields", :f => builder %>
<% end %>
 <%= f.buttons do %>
  <%= f.commit_button "Speichern"%>
<% end %> 
<% end %>

In the partial is this, will later be extended

<%= f.inputs :date%>

Now I get the form with the correct three date fields and I can save the Exam itself correctly. When I look at params[:exam][:examdates_attributes] the dates are there:

{"0"=>{"date(1i)"=>"2006", "date(2i)"=>"1", "date(3i)"=>"1"},
 "1"=>{"date(1i)"=>"2006", "date(2i)"=>"1", "date(3i)"=>"1"},
 "2"=>{"date(1i)"=>"2006", "date(2i)"=>"1", "date(3i)"=>"1"}}

But when I put Exam.find(1).exdates in my rails Console, I get []. I really don´t have any idea what I did wrong, so every little tip is very appreciated:)

有帮助吗?

解决方案

Since you are using attr_accessible in your Exam model, I think you'll have to include :examdates_attributes in that list. Otherwise, mass assignment to the nested model will not be allowed.

class Exam < ActiveRecord::Base
  attr_accessible :title, :prof_id, :deadline, :examdates_attributes
  ...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top