【发布时间】:2018-11-01 17:56:42
【问题描述】:
我是编码初学者。抱歉,如果这是一些简单的答案,但我一直在寻找几个小时,但没有运气。
当前问题:2018 年 5 月存在 1 次运行。
在我的 /months 索引页面上,有一个指向 2018 年 5 月 页面的链接,我可以在该页面上创建本月的未来运行。
但是,如果我创建了第二次运行,当我导航回我的 /months 索引页面时,会显示到 2018 年 5 月的两个链接(不像我预期的那样)。 在数据库中,2018 年 5 月只有一个对象,并且它拥有两个运行。 (然后当我创建更多运行时,它变为 3、4、5、6 等链接......)
快速总结:这是一个运行日志应用程序。一个月 has_many 运行。
当我创建一个运行时,它附加到一个月。
runs_controller.rb
def create
@run = @month.runs.build(run_params)
@run[:user_id] = current_user.id
@run[:pace_per_mile] = @run.format_pace_per_mile
if @run.save
redirect_to month_path(@month)
else
@month = Month.find(params[:month_id])
@runs = @month.runs
render 'months/show'
end
end
这是发生错误的 /month index.html.erb 代码:
<strong><h2>Your Previous Runs</h2></strong>
<% @months.each do |month| %>
<%= link_to(month) do %>
<h3><%= month.name %> <%= month.year %></h3>
<% end %>
<% end %>
这是我的月份#index,因此您可以查看范围。
def index
@months = current_user.months
@month = Month.new
end
如果我不包含某些内容,我可以提供更多代码!
@xploshioOn、@fool-dev 和 @moveson,感谢您的回复。
我包括月份和用户模型,以及创建月份的代码...
月.rb
class Month < ApplicationRecord
has_many :runs
has_many :users, through: :runs
validates :name, :year, presence: true
def month_mileage
self.runs.collect {|run| run.distance}.sum
end
end
用户.rb
class User < ApplicationRecord
has_secure_password
validates :email, presence: true
validates :email, uniqueness: true
validates :password, presence: true
validates :password, confirmation: true
has_many :runs
has_many :months, through: :runs
end
我目前正在从 months_controller 创建月份。我开始觉得这是我的错误所在?
def create
@month = Month.new(month_params)
if @month.save
redirect_to month_url(@month)
else
@months = current_user.months
render :index
end
end
再次感谢您的建议!
【问题讨论】:
-
请添加用户和月份的型号。
-
代码好像没问题,我认为问题出在
relationships这样的模型上,能否请您显示有关系的模型 -
@xploshioOn,傻瓜开发者和 moveson,我已经添加了更多的 sn-ps,正如你所问的。谢谢你的时间。当我查看代码时,我认为问题可能出在我的人际关系上?那几个月和用户只通过join table(runs)相关?