Rails 3 Nested Models unknown attribute Error

前端 未结 4 1968
时光取名叫无心
时光取名叫无心 2021-01-03 03:49
  • I have a model \"Issue\" and a nested Model \"Relationship\"
  • In the issue.rb I have mentioned:

    has_many :relationships, :dependent => :d         
    
    
            
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-03 04:55

    Here is the working skeleton code: I created a new project and tried the combination of the other answers, and finally made it to work.

    Here is my solution, after that are the things to watch out for. I am using different models so bear with me:

    • My models are: discussion has_many posts.
    • Discussion has no attributes.
    • Posts has content:text and discussion_id:integer.

    Working Code

    (model) discussion.rb

    has_many :posts
    accepts_nested_attributes_for :posts
    

    (model) post.rb

    belongs_to :discussion
    

    routes.rb

    resources :discussions do
      resources :posts
    end
    

    (discussion view) _form.html.erb

    <%= form_for(@discussion) do |f| %>
      <%= f.fields_for :posts, @post do |p| %>
        <%= p.text_area :content %>
      <% end %>
      <%= f.submit %>
    <% end %>
    

    (controller) discussions_controller.rb

      def new
        @discussion = Discussion.new
        @post = @discussion.posts.build
    
        respond_to do |format|
          format.html # new.html.erb
          format.xml  { render :xml => @discussion }
        end
      end
    
      def create
        @discussion = Discussion.new(params[:discussion])
    
        respond_to do |format|
          if @discussion.save
            format.html { redirect_to(@discussion, :notice => 'Discussion was successfully created.') }
            format.xml  { render :xml => @discussion, :status => :created, :location => @discussion }
          else
            format.html { render :action => "new" }
            format.xml  { render :xml => @discussion.errors, :status => :unprocessable_entity }
          end
        end
      end
    

    Possible things that can go wrong

    First, Thilo was right, I get unknown attribute: post if I do

    # WRONG!
    f.fields_for :post
    

    Second, I have to have the @post instance variable in new action otherwise the post.context textarea will not show up.

    # REQUIRED!
    @post = @discussion.posts.build
    

    Third, If I use the f.fields_for @post, the create action will complain unknown attribute: post too.

    # WRONG!
    f.fields_for @post do |p|
    

    Use this instead:

    # RIGHT!
    f.fields_for :posts, @post  do |p|
    

    The End

    So yeah, I wish we get to see more documentations on this (can't see any useful ones). For example I see some use of form_for [@discussion, @post] but I can never get it to work.

提交回复
热议问题