Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 4 如何使用与select有多大关系?_Ruby On Rails 4_Has Many - Fatal编程技术网

Ruby on rails 4 如何使用与select有多大关系?

Ruby on rails 4 如何使用与select有多大关系?,ruby-on-rails-4,has-many,Ruby On Rails 4,Has Many,给定问题和观察者模型: class Problem < ActiveRecord::Base has_many :observers accepts_nested_attributes_for :observers end class Observer < ActiveRecord::Base belongs_to :problem belongs_to :user end 然而,Rails为select生成了错误的名称:问题[Observators\u attr

给定
问题
观察者
模型:

class Problem < ActiveRecord::Base
  has_many :observers
  accepts_nested_attributes_for :observers
end

class Observer < ActiveRecord::Base
  belongs_to :problem
  belongs_to :user
end
然而,Rails为select生成了错误的名称:
问题[Observators\u attributes][0][user\u id][
,因此即使为强参数(
{:Observators\u attributes=>[{:user\u id=>[]}}
)创建了错误的关系,只有问题id进入数据库,所有用户id都被忽略

我想做的是在多个select、grab id中显示所有用户,并在
Problem#new
方法中为他们创建关联

更新12.10

发布的参数:

def problem_params
 params.require(:problem).permit({:files_attributes => [:attach_id]}, {:observers_attributes => {:user_id => []}}, {:problem_data_attributes => [:title, :description]})
end
参数:
{“utf8”=>“✓", "真实性令牌“=>”NHDl/hrrFgATQOoz9A3OLbLDAbTMziKMQW9X1y2E8Ek=“,”问题“=>{”问题数据属性“=>{”标题“=>”SAFASFASF“,”描述“=>”,”观察员属性“=>{”0“=>{”用户id“=>[“5”,“8”]}}}}}

strong参数:

def problem_params
 params.require(:problem).permit({:files_attributes => [:attach_id]}, {:observers_attributes => {:user_id => []}}, {:problem_data_attributes => [:title, :description]})
end
创建方法

def create
 @problem         = @project.problem.build(problem_params)
 @problem.account = current_account

 if @problem.save
  render :json => {status: true, id: @problem.id}
 else
  respond_with(@problem)
 end
end
和在创建调用期间创建观察者的SQL

SQL (0.2ms)  INSERT INTO `observers` (`problem_id`) VALUES (96)

在您这样做的方式中,您是说您只需要一个具有多个用户ID的观察者,实际上您需要的是每个用户(和问题)一个观察者

您可能应该使用如下关联模型:

请记住按字母顺序创建关联,在您的案例中,是ModelProblemUser和TableProblems\u users

然后,你可以这样做:–请阅读问题和答案,以便更好地理解


希望有帮助。

你所做的应该有用。rails为选择菜单生成的内容也正确。你试过看看你的params散列里有什么吗?还有,你是否保存了这个,你的控制器是什么样子的?@jokklan yeap,我正在接收
“观察员属性”=>{“0”=>{“用户id”=>[[0]“5”]}
作为散列,rails生成SQL(0.2ms)
插入观察员(问题id)值(58)
,其中58是一个问题id,但是忽略了用户id。那么,在您的参数中还必须有一个
“problem\u id”=>“58”
?对于强参数,您的许可证和要求选项是什么?你可以发布你的整个控制器动作吗?@jokklan,不,问题是rails造成的。我在问题中添加了代码和日志。这很有帮助,因为额外的ACL验证,我切换到has_many through,但再次感谢您将我指向habtm关系。