2016-05-29 66 views
0

我有一个用户模型和一个朋友模型(朋友继承自用户类)。用户通过友谊连接模型拥有许多朋友。红宝石轨道上的未知属性错误4

用户还可以创建消息并将它们发送给他们的朋友。我希望能够跟踪哪些消息发送给哪些朋友。 因此,我创建了一个消息模型,该模型与友谊模型结合在一起以创建关联的sent_messages模型。

class User < ActiveRecord::Base 
    has_many :friendships 
    has_many :friends, :through => :friendships 

    has_many :messages 
end 

class Friendship < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :friend, :class_name => 'User' 

    has_many :sent_messages 
    has_many :messages, :through => :sent_messages 
end 

class Message < ActiveRecord::Base 
    belongs_to :user 

    has_many :sent_messagess 
    has_many :friendships, :through => :sent_messages 
end 

class SentMessage < ActiveRecord::Base 
    belongs_to :message 
    belongs_to :friendship 
end 

在消息创建表单会有数据的文本框和一个复选框上市,他们可以选择将消息发送给用户的所有朋友。

<%= form_for @message, url: user_messages_path do |f| %> 

    <div class="form-group"> 
     <%= f.text_field :title %> 
    </div> 

    <div class="form-group"> 
     <%= f.text_area :message %> 
    </div> 

    <% Friendship.all.each do |friendship| -%> 
     <div> 
      <%= check_box_tag('message[friendships_id][]',friendship.id,@message.friendships.include?(friendship.id))%> 
      <%= label_tag friendship.friend_username %> 
     </div> 
    <% end -%> 

    <div class="actions"> 
    <%= f.submit "Send", class: 'btn btn-primary' %> 
    </div> 
<% end %> 

这里是消息控制器

class MessagesController < ApplicationController 
    before_action :authenticate_user! 

    def create 
    @message = Message.new(message_params) 
    if @message.save 
     redirect_to action: "show", id: @message.id 
    else 
     respond_to do |format| 
      format.html 
      format.js 
     end 
    end 
    end 

    private 

    def message_params 
     params.require(:message).permit(:title,:message,:friendships_id => []) 
    end 
end 

这里是架构

create_table "messages", force: true do |t| 
    t.integer "user_id" 
    t.string "title" 
    t.text  "message" 
    end 
    create_table "sent_messages", force: true do |t| 
    t.integer "message_id" 
    t.integer "friendships_id" 
    end 
    create_table "friendships", force: true do |t| 
    t.integer "user_id" 
    t.integer "friend_id" 
    t.string "friend_username" 
    end 

当我提交的消息,我得到的错误 “未知属性:friendships_id” 不知道如何纠正这一点。

回答

0

您正在尝试在创建@message时传递friendships_id,但数据库中的消息表中没有friendships_id列,导致此错误为“未知属性:friendships_id”。

除此之外,您在关联和迁移中遇到了一些错误。

  1. has_many :sent_messagess应该has_many :sent_messages

  2. 改变你的 'sent_messages' 表来更改列 'friendships_id' 到 'friendship_id'

+0

这工作!谢谢 –