2016-05-29 98 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

這工作!謝謝 –