0
我有一個奇怪的問題,我想不通。Rails的關聯不起作用
這是非常基本的Rails編程:我想創建一個用戶模型和目標模型之間的關聯。
goal.rb
class Goal < ActiveRecord::Base
belongs_to :user
end
user.rb
class User < ActiveRecord::Base
has_many :goals, dependent: :destroy
has_many :records
has_many :orders
end
當我正在從控制檯的關聯,它運作良好,可以說:
$ goal = Goal.first
$ goal.user_id = 1
$ goal.save
$ goal.inspect
#<Goal id: 1, description: "loremipsum", created_at: "2016-11-26 12:39:34", updated_at: "2016-11-26 12:43:41", name: "ipsumlorem", user_id: 1>
但後來,當我根據我的觀點創建一個目標,不建立關聯,並且目標user_id的user_id仍爲:無。
任何想法?
根據需要編輯:
_form.html.erb
<%= form_for(@goal) do |f| %>
<%= f.text_field :name, class: "form-control" %>
<%= f.text_area :description, class: "form-control" %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
goal_controller.rb
def new
@users = User.all
@goal = current_user.goals.build
end
def edit
end
def create
@goal = Goal.new(goal_params)
@goal.save
redirect_to root_path, notice: "Objectif sauvegardé"
end
你能告訴你的看法和你的控制器代碼,而不是作爲問題更多的是關於視圖和控制器的問題。 – vee
@vee做 - '在'create'行動更新了意見代碼 – zacchj
如果你'@goal = current_user.goals.build(goal_params)會發生什麼?你做'Goal.new(goal_params)''那裏goal_params'沒有'user_id'一套,因爲你不把它提供給'goal_params'以任何方式。 – vee