【问题标题】:Using .build method to create through 1to1 association使用 .build 方法通过 1to1 关联创建
【发布时间】:2011-11-17 07:04:42
【问题描述】:

我与简单的用户模型和配置文件模型具有一对一的关系:

模型/用户

class User < ActiveRecord::Base
  authenticates_with_sorcery!

  attr_accessible :email, :password, :password_confirmation

  has_one :profile, :dependent => :destroy

  validates_presence_of :password, :on => :create
  validates :password, :confirmation => true,
                       :length       => { :within => 6..100 }

  email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, :presence        => true,
                    :format          => { :with => email_regex },
                    :uniqueness      => {:case_sensitive => false},
                    :length          => { :within => 3..50 }
end

模型/配置文件

            # == Schema Information
    #
    # Table name: profiles
    #
    #  id         :integer         not null, primary key
    #  weight     :decimal(, )
    #  created_at :datetime
    #  updated_at :datetime
    #

    class Profile < ActiveRecord::Base
      attr_accessible :weight

      belongs_to :user

    end

我这样做是因为我希望用户能够随着时间的推移跟踪体重,并在个人资料中存储其他更静态的数据,例如身高。

但是,我的 new 和 create 方法似乎无法正常工作。我在提交新操作时收到此错误:

undefined method `build' for nil:NilClass

profile_controller

class ProfilesController < ApplicationController

  def new
    @profile = Profile.new if current_user
  end

  def create
    @profile = current_user.profile.build(params[:profile])
    if @profile.save
      flash[:success] = "Profile Saved"
      redirect_to root_path
    else
      render 'pages/home'
    end
  end

  def destory
  end

end

和新的配置文件视图

<%= form_for @profile do |f| %>
    <div class="field">
        <%= f.text_field :weight %>
    </div>
    <div class="actions">
        <%= f.submit "Submit" %>
    </div>
<% end %>

提前感谢您提供的任何帮助。菜鸟在这里!

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    has_one 关联的构建语法与 has_many 关联不同。 更改代码如下:

    @profile = current_user.build_profile(params[:profile])
    

    参考:SO Answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 2023-04-04
      • 2017-07-21
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      • 2017-11-12
      相关资源
      最近更新 更多