工作走在掌握这个Rails的东西!
我有一个主题(如论坛),而我试图关联到一个章节(类别)。我能够列出新的页面上可用的章节,但是当我保存,我不能得到正常的保存。
topics_controller.rb
def create
@topic = Topic.new(topic_params)
@topic.user = current_user
@topic.chapter = Chapter.find(params[:chapter_id])
在我的形式
<%= f.collection_select :chapter_id, Chapter.all, :id, :name %>
我将不胜感激任何人的帮助! :)
如果你不介意的话,我将我的评论转化为答案,不离回答此问题。
看看服务器日志。我想,则params像topic: { chapter_id: 1}
。这意味着,你可以通过params[:topic][:chapter_id]
访问所需的参数。但更好的方法是chapter_id
添加到允许PARAMS(topic_params)。在这种情况下,您可以简化创建动作有点
# note - you can create a topic belonging to current_user in one line
def create
@topic = current_user.topics.build(topic_params)
if @topic.save
redirect to topics_path
else
render :new
end
end
def topic_params
params.require(:topic).permit(:title, :text, :all_other_parameters, :chapter_id)
end
你需要在链接使用章节的名字。假设它是title
属性:
<%= link_to topic.chapter.title, topic.chapter %>