2015-07-20 39 views
2

我使用的是react-rails gem,並且有兩個模型:MessageUser。用戶has_many:消息。使用React導軌顯示關聯的模型數據

在我的message.js.jsx中,我想顯示該消息的用戶。在常規的erb中,它只是<%= message.user.name %>。我如何在message.js.jsx組件中執行此操作?

回答

2

可以你的組件重命名爲message.js.jsx.erb並在其使用ERB,但其會在Rails的啓動時只被編譯一次。

更多React-ish處理方法是將AJAX加載componentDidMount(或Store,如果使用Flux)中的用戶數據。

message.js.jsx

getInitialState: function() { 
    return { user: { name: '' } }; 
}, 

componentDidMount: function() { 
    $.getJSON('/users/'+ this.props.id +'.json', function(userData) { 
    if (this.isMounted()) { 
     this.setState({ user: userData }) 
    } 
    }); 
}, 

您可以創建一個Rails終點返回用戶數據作爲JSON是這樣的:

users_controller.rb

def show 
    @user = User.find(params[:id]) 
    respond_to do |format| 
    format.html # default html response 
    format.json { render json: @user.to_json(only: [:id, :name]) } 
    end 
end 

Facebook's page on this瞭解更多詳情

1

我同意Unixmonkey的反應方式。你也可以做更多的方法。

@user = JSON.parse user.to_json(include: [:messages], only: [:id, :name]) 

除了使用componentDidMount擊中使用JBuilder中,你可以把一個超時,如果你要可以動態地更新一個JSON端點。

componentDidMount: function() { 
    $.getJSON('/users/'+ this.props.id +'.json', function(user) { 
    if (this.isMounted()) { 
     this.setState({ user: user }) 
    } 
    }); 
}, 

你下用戶意見show.json.jbuilder會是這個樣子:

json.id @user.id 
    json.name @user.name 
    json.messages @user.messages do |message| 
    json.id message.id 
    json.content message.content 
    json.created_at message.created_at 
    end