小编Mik*_*ike的帖子

如何将记录添加到has_many:通过rails中的关联

class Agents << ActiveRecord::Base
  belongs_to :customer
  belongs_to :house
end

class Customer << ActiveRecord::Base
  has_many :agents
  has_many :houses, through: :agents
end

class House << ActiveRecord::Base
  has_many :agents
  has_many :customers, through: :agents
end
Run Code Online (Sandbox Code Playgroud)

如何添加Agents模型Customer

这是最好的方法吗?

Customer.find(1).agents.create(customer_id: 1, house_id: 1)
Run Code Online (Sandbox Code Playgroud)

以上工作正常从控制台,但我不知道如何在实际应用程序中实现这一点.

想象一下,为客户填写的表格也house_id作为输入.然后在我的控制器中执行以下操作?

def create 
  @customer = Customer.new(params[:customer])
  @customer.agents.create(customer_id: @customer.id, house_id: params[:house_id])
  @customer.save
end
Run Code Online (Sandbox Code Playgroud)

总的来说,我对如何在has_many :through表中添加记录感到困惑?

activerecord ruby-on-rails has-many-through

91
推荐指数
3
解决办法
9万
查看次数

haml条件if/else缩进

我有一种情况,我想只在count大于0时才将类添加到div标签

例:

- @color.shades.each_with_index do |shade, index|
    - if index == 0
        #shades
    - else
        #shades.horizontalLine.second
     %h3 something
     %dl 
         %dt some
         %dd some1
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我想要的一切,从开始%h3来在任#shades#shades.horizontalLine.second因这些不过如果和else语句评估.

解决方法是:

- @color.shades.each_with_index do |shade, index|
    - if index == 0
        #shades
          %h3 something
            %dl 
              %dt some
              %dd some1
    - else
        #shades.horizontalLine.second
          %h3 something
            %dl 
              %dt some
              %dd some1
Run Code Online (Sandbox Code Playgroud)

但在这里我必须重复代码

我很困惑如何在rails中执行此操作而不重复从%h3两个div 开始的代码.

haml ruby-on-rails

5
推荐指数
1
解决办法
3053
查看次数

ruby正则表达式在字符串中找到前两个数字

如果我有一个字符串

6d7411014f
Run Code Online (Sandbox Code Playgroud)

我想读取前两个整数的出现,并将最终的数字放在一个变量中

基于上面的例子我的变量将包含 67

更多例子:

d550dfe10a
Run Code Online (Sandbox Code Playgroud)

变量将是 55

我试过的是\d但是这给了我6.如何得到第二个数字?

ruby regex

1
推荐指数
2
解决办法
3510
查看次数