我有这种纤细的语法:
= form_for(@influencer.relationships.build(followed_id: @influencer.id)) do |f|
div = f.hidden_field :followed_id
= f.submit "Follow", class: "btn btn-large btn-primary"
这是我提出的问题,但它不起作用。
<%= form_for(@influencer.relationships.build(followed_id: @influencer.id)) do |f| %>
<% f.hidden_field :followed_id %>
<%= f.submit "Follow" %>
<% end %>
答案 0 :(得分:0)
<%= form_for @influencer.relationships.build(followed_id: @influencer.id) do |f| %>
<%= f.hidden_field :followed_id %>
<%= f.submit "Follow" %>
<% end %>
相反,从控制器范围构建对象是不好的做法。 @influencer.relationships.build(followed_id: @influencer.id)
应该在控制器内完成:
#app/models/influencer.rb
class Influencer < ActiveRecord::Base
has_many :relationships, foreign_key: :follower_id
end
#app/controllers/relationships_controller.rb
class RelationshipsController < ApplicationController
def new
@influencer = Influencer.find params[:influencer_id]
@relationship = @influencer.relationships.build #-> "followed_id" SHOULD be a foreign key in the model. If you have it in the model, you won't need to explicitly define it
end
end
因此,你会得到:
<%= button_to "Follow", @relationship %>