【问题标题】:Rails Multiple AssociationsRails 多个关联
【发布时间】:2015-02-12 05:37:00
【问题描述】:

我在设置关联时遇到问题。我正在尝试将Courses 设置为具有不同的Prices,具体取决于Seasonalumns 的数量。当Seasons 对同一个Season 有不同的日期范围时,情况会变得更加复杂,例如第一个Season 是从 2014 年 12 月 24 日到 2014 年 12 月 31 日,也从 2015 年 1 月 7 日到2015 年 1 月 14 日。为此我创建了另一个模型Season_dates

我不知道如何建立我的关联,这是我目前得到的:

class Season < ActiveRecord::Base
 has_many :season_dates
 has_many :prices, through: :season_dates
end

class SeasonDate < ActiveRecord::Base
 belongs_to :price
 belongs_to :seasons
end

class Price < ActiveRecord::Base
 belongs_to :course
 has_many :season_dates
 has_many :seasons, through: :season_dates

 accepts_nested_attributes_for :season_dates
end

class Course < ActiveRecord::Base
 has_many :prices
end

表格:

<%= form_for @price do |f| %>
<div class="field">
<%= f.fields_for :couse do |course_f| %>
  <%= course_f.label :course %><br>
  <%= course_f.collection_select :course_id, Course.all, :id, :name, {}, {class: 'form-control'} %>
<% end %>
</div>
<div class="field">
 <%= f.label :alumn %><br>
 <%= f.number_field :alumn, in: 1...11, step: 1, class: 'form-control' %>
</div>
<div class="field">
 <%= f.fields_for :season_date do |season_f| %>
  <%= season_f.label :season %><br>
  <%= season_f.select :season_id, options_from_collection_for_select(Season.all, :id, :name), {}, {class: 'form-control'} %>
 <% end %>
</div>
<div class="field form-group">
 <%= f.label :price %><br>
 <%= f.number_field :price, in: 0.01..999.99, step: 0.01, placeholder: "0.00€", class: 'form-control' %>
</div>
<div class="actions">
 <%= f.submit class: 'btn btn-default' %>
</div>
<% end %>

我希望能够致电price.season.nameprice.course.name。我不确定如何继续,感谢任何帮助。

【问题讨论】:

  • 使用包含和通过关系

标签: ruby-on-rails ruby-on-rails-4 model-view-controller associations


【解决方案1】:

我认为您可能会使情况稍微复杂化。 SeasonDate 是它自己的类有什么原因吗?有没有办法可以这样建模?

class Season < ActiveRecord::Base

  has_many :courses

  # I would have on this model the attributes of from_date and
  # to_date removing the need for a SeasonDate class

end

class Course < ActiveRecord::Base

  belongs_to :season

  # You might need to model this as a has_and_belongs_to_many relationship
  # with a Season if a Course can belong to many seasons

end

class Price < ActiveRecord::Base

  belongs_to :course
  belongs_to :season

end

这些模型将为您提供以下方法:

@season.courses # would return all courses in a particular season
@price.season.name
@price.course.name
@course.prices # would return all prices associated with a particular course

如果您确实选择了 habtm 关联,这意味着一门课程可以属于多个季节,您可以在您的视图中执行类似的操作(猜测您的价格属性名称)。

<%= @course.name %>
<% @course.prices.each do |price| %>
 <%= price.season.name %> : <%= price.price_in_dollars %>
<% end

这将允许您遍历课程的所有价格并显示它们适用于哪个季节,以便每个人都能找到最适合他们的价格。

【讨论】:

  • 你说得对,我太复杂了。我的问题是强参数,没有传递正确的模型ID。谢谢你的回答,对我帮助很大。
猜你喜欢
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
  • 2011-06-08
  • 1970-01-01
  • 1970-01-01
  • 2014-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多