Ruby on rails 未在中创建的Rails:JOIN有多个:通过关系
最初,我有两个模型:“用户”和“线程”。用户有许多线程,线程有一个用户 现在,我添加了一个名为“Publications”的连接,并调整了原始的“Users”和“Thread”模型。但是,当我创建一个新线程时,没有任何记录被添加到联接表(发布),并且“Threads”表中的“user_id”列为null–没有错误 ------更新------------Ruby on rails 未在中创建的Rails:JOIN有多个:通过关系,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,最初,我有两个模型:“用户”和“线程”。用户有许多线程,线程有一个用户 现在,我添加了一个名为“Publications”的连接,并调整了原始的“Users”和“Thread”模型。但是,当我创建一个新线程时,没有任何记录被添加到联接表(发布),并且“Threads”表中的“user_id”列为null–没有错误 ------更新------------ 我已经取得了一些进展–发布现在正在成功创建,并使用线程id保存。但是,用户id仍然为空。我在下面添加了控制器操作 以下是我的用户模型: cla
我已经取得了一些进展–发布现在正在成功创建,并使用线程id保存。但是,用户id仍然为空。我在下面添加了控制器操作 以下是我的用户模型:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation,
:remember_me, :username, :profile_image,
:first_name, :last_name
has_many :publications
has_many :threads, :through => :publications
end
以下是我的控制器操作:
def create
@user = User.find(params[:user_id])
@thread = @user.threads.new(params[:thread])
@thread.build_publication
end
在控制器中:
@user = User.find(params[:id])
@thread = @user.threads.create(params[:thread])
请编辑您的问题,将控制器操作发布到您正在创建模型和关系的位置。我取得了一些进展–发布现在已成功创建,并使用线程id保存。但是,用户id仍然为空。我已经在下面添加了控制器操作。请尝试
@thread.publication.create
而不是build。感谢@Gene,看起来build\u publication工作正常–现在,唯一未决的问题是创建发布时user\u id为null
= form_for [@user, @thread] do |f|
- if @thread.errors.any?
#error_explanation
%h2= "#{pluralize(@thread.errors.count, "error")} prohibited this thread from being saved:"
%ul
- @thread.errors.full_messages.each do |msg|
%li= msg
.field
%span Title:
= f.text_field :name
.actions
= f.submit 'Submit'
def create
@user = User.find(params[:user_id])
@thread = @user.threads.new(params[:thread])
@thread.build_publication
end
@user = User.find(params[:id])
@thread = @user.threads.create(params[:thread])